Vishnu Paspunoor Vishnu Paspunoor - 3 months ago 7
Javascript Question

Difference between two ways of adding properties to object in Javascript

My code involves adding properties to an object based on some test cases. Here are the two ways i which I did it. I am using this object for inline styling in reactjs.

var myObject = {}

//some code

myObject = {
key1: value1,
key2:value
}

//some code

myObject = {
key3: value3,
key4: value4
}


All the properties(styles) were not applied consistently. So I tried doing this instead and it worked properly. Please explain why this is happening.

var myObject = {}

//some code

myObject = {
key1: value1,
key2:value
}

//some code

myObject.key3 = value3;
myObject.key4 = value4;


What is the difference between these two ways?

Answer

In the first snippet you are not adding properties to an object, you are overwriting the whole myObject. In the second snippet you are assigning a single value to a key instead, ie. adding properties with values.

For example:

var i = {num: 1};
i.num = 2;
console.log(i.num); // 2
i = {str: "Hello"};
console.log(i.num); // undefined
console.log(i.str); // "Hello"
i.num = 1;
console.log(i.num); // 1
console.log(i.str); // "Hello"