Adeel Imran
Adeel Imran

Reputation: 13966

What is the difference between { something: value } & Object.assign({}, { something: value })

I am learning react & redux. I wanted to find the difference between these two codes.

export default function xReducer (state = [], action) {
    switch (action.type) {
        // I am simply assigning my key value to the action property
        case 'SOMETHING': {
             return [ ...state, { myKey: action.x } ]
        }
        // I am using Object.assign
        case 'SOMEMORE': {
             return [ ...state, Object.assign({}, { myKey: action.x }) ]
        }
    }
}

Upvotes: 4

Views: 118

Answers (2)

roland
roland

Reputation: 7775

The usage of Object.assign in your example provides no benefit. Object.assign creates a shallow copy. Basically using Object.assign will create a new instance of an object keeping the original object intact. In React terminology, it's all about keeping your object immutable.

var obj1 = {prop1: "A"};
var obj2 = Object.assign({}, obj1);
obj1 === obj2; //false as they are 2 different instances

This can be achieved doing:

var obj2 = {
  prop1: obj1.prop1
};
obj1 === obj2; //false as they are 2 different instances

Note that Object.assign works well for primitive types (string, number, boolean for the most significant ones) as they are all immutable types (cannot be changed). Object.assign will not create a new instance of reference types such as Array, Function, Object, null, undefined.

Example:

var obj3 = {
  fn: function() {}
};

var obj4 = Object.assign({}, obj3);
obj3.fn === obj4.fn; //true as Object.assign will not create a new instance of fn

When used properly, Object.assign is versatile and powerful.

See Mozilla's page: https://developer.mozilla.org/en-US/docs/Glossary/Primitive

Upvotes: 1

Mark Reed
Mark Reed

Reputation: 95252

To the best of my knowledge, in this particular example, there is no difference. You use Object.assign to combine multiple objects where there may be overlapping keys, such that the value of those keys in objects to the right override the value in objects to the left. The canonical example is something like this:

let options = Object.assign({}, defaultOptions, passedOptions)

In this case, since the only objects being merged are an empty one and a single literal one, the result is the same as the literal one by itself.

Upvotes: 3

Related Questions