2

If I type this into console:

var x = {a: 1};
var y = Object.create(x);
console.log(y);

It shows {}. But if I run it in fiddle it shows {a: 1}, which is the expected result. Also here:

var x = {a: 1};
var y = Object.create(x);
console.log(y);

So what is going on?

2
  • Your snippet above shows { "a": 1 }.. for me. Commented Jun 8, 2021 at 21:48
  • 1
    Because Object.create doesn't clone anything. It creates a new (empty) object that inherits. Commented Jun 8, 2021 at 21:56

2 Answers 2

3

Answer

Why doesn't Object.create clone properties as expected?

Because Object.create isn't supposed to clone properties.

JavaScript objects are tricky

If we look at the documentation of Object.create, it says:

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

Besides its own properties, each object in JavaScript also inherits properties from its prototype.

Now, the tricky part is – inherited properties are only visible in some cases. For example:

  • Property accessor – y.a or y['a'] – ✅ sees inherited properties
    • console.log(y.a); // outputs 1
  • Object.keys, Object.values, Object.entries – ❌ doesn't see inherited properties
    • console.log(Object.keys(y)); // outputs []

These concepts are much more comprehensively covered in Enumerability and ownership of properties.

For a more thorough explanation of prototypes, see Object prototypes.

Why does JSFiddle print it differently than Chrome?

Apparently, JSFiddle's implementation of console enumerates inherited properties, whereas Chrome's console implementation doesn't.

Sign up to request clarification or add additional context in comments.

1 Comment

Wish I could upvote this thrice - once for each part of the explanation :-)
2

Runs as expected even in console. You just have to extend the Object.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.