Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In JavaScript does the placement and ordering of a spread operator matter?

var item = {/* key value pairs here */};
var itemB = {/* key value pairs here */};

For example in the following code snippets will newItem always have the same key value pairs?

var newItem = {
    ...item,
    ...itemB
};

as

var newItem = {
    ...itemB,
    ...item
};
like image 444
Charlie Fish Avatar asked Jul 30 '18 17:07

Charlie Fish


1 Answers

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.

like image 105
Charlie Fish Avatar answered Sep 21 '22 20:09

Charlie Fish