Diablo3093
Diablo3093

Reputation: 1063

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?

Upvotes: 0

Views: 81

Answers (3)

Ivan Shmidt
Ivan Shmidt

Reputation: 173

Consider using Object.assign in first case, cause otherwise myObject would contain only key3 and key4.

var myObject = {}

//some code

myObject = {
  key1: value1,
  key2:value
} 

//some code

Object.assign(myObject,{
  key3: value3,
  key4: value4
})

Upvotes: 1

Shambhu Kumar
Shambhu Kumar

Reputation: 26

There is difference between the two cases

the first case:

myObject = { key1: value1, key2:value }

means creating a new object and assigning it to variable myObject

While in the second case:

myObject.key3 = value3;

myObject.key4 = value4;

mean adding new property/value to the existing object.

Upvotes: 0

tedcurrent
tedcurrent

Reputation: 431

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"

Upvotes: 1

Related Questions