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
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With