4

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 }) ]
        }
    }
}
1
  • 3
    Technically this is just ES6, nothing to do with React or Redux really. Mosto of the times Object.assign is used to make a shallow copy of an object, in this case it doesn't look necessary. Commented Feb 19, 2017 at 18:07

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.