JavaScript - Does the placement/order of spread operator in an object matter? JavaScript - Does the placement/order of spread operator in an object matter? json json

JavaScript - Does the placement/order of spread operator in an object matter?


Besides just the general order of the key value pairs, which doesn't really have a super major impact on the result of the object, the only other difference would be if item and itemB have duplicate keys.

For example.

var item = {firstName: "Bob"};var itemB = {lastName: "Smith", firstName: "Tim"};

In this case the following two items will not be identical.

var newItem = {    ...item,    ...itemB};// {lastName: "Smith", firstName: "Tim"}

-

var newItem = {    ...itemB,    ...item};// {lastName: "Smith", firstName: "Bob"}

So if there are duplicate keys the order of the spread opperator does matter.

This can be especially useful if you wish to provide default key value pairs for an object. You can just put the default key value pairs before the spread operator and it will act as defaults for the new object if they don't exist in the object that is being used in the spread operator.