Spread Operator Behavior

I do not understand the placement of new things with the spread operator. The expected behavior was the new object key and value would be added to the end of the object, but instead it was inserted in the second to last spot. Can anyone tell me why? Code posted below

const animals = { lion: 5, tiger: 23, bear: 11, giraffe: 3, antelope: 7 };

const newAnimals = { ...animals, penguin: 2 };

console.log(animals);
console.log(newAnimals);

animals result

{lion: 5, tiger: 23, bear: 11, giraffe: 3, antelope: 7}
antelope
: 
7
bear
: 
11
giraffe
: 
3
lion
: 
5
tiger
: 
23
[[Prototype]]
: 
Object

newAnimals result

{lion: 5, tiger: 23, bear: 11, giraffe: 3, antelope: 7, …}
antelope
: 
7
bear
: 
11
giraffe
: 
3
lion
: 
5
penguin
: 
2
tiger
: 
23
[[Prototype]]
: 
Object

I see now that it automatically put it into alphabetical order according to the keys. I still do not understand why it does this. Is there a way to return it in the original order and to ensure something is added to END?

The ‘spread’ operator does exactly what is expected:


It expands the ‘newAnimals’ object into more elements of the “key-value” type, adding the ‘penguin’ property and its value at the end.

1 Like

Thank you for your reply, I see where I confused myself. Since the object was a bit too large for my screen it did not show the rest of the object, so when I expanded it in the console that is where it went into alphabetical order, not in the actual output of the new object. Thanks again for verifying that it works as expected

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.