Difference Object.create with object literal in spread operator

Viewed 64

In this case, object created from object literal and Object.create had difference result in spread operator. From what i know, spread operator just spread own properties not inherited properties, but in this case why in object literal the result is 1 not undefined? Isn't o inheriting to p?

let o = {x: 1}; 
let p = { ...o };
console.log(p.x) // => 1

let q = Object.create({y: 1}); 
let r = { ...q };
console.log(r.y) // => undefined
1 Answers

There is a difference between Object.create() and literal objects. When using Object.create you are asking JavaScript to create a new object and inherit everything from the object which has been passed. Basically, if you change your code like this:

let baseObject = {y: 1};
let q = Object.create(baseObject);

Here you are basically creating a new object which in its prototype chain inherits the y from baseObject. So you can check that Object.keys(q) does not contain the y key since it is being inherited from its __proto__ object:

Object.keys(q); // []

But:

Object.keys(q.__proto__); // ["y"]

And this is because:

console.log(q.__proto__ === baseObject); // true

The spread operator only spreads the keys that exist directly in the first level of your object and it does not go through the prototype chain.

To learn more about this topic you can have a look at this article: Inheritance and the prototype chain

Related