0

Does JavaScript creates object literal with Object constructor under the hood?

when we do let obj = {}; and console.log(obj.__proto__) it prints an object with constructor so does that mean object literal is being created by Object constructor under the hood

2
  • 1
    No. But both {} and the new Object constructor use the same internal mechanism under their hoods. Commented Aug 19, 2021 at 20:12
  • 2
    "it prints an object with constructor" - all that means is that objects created from literal inherit from Object.prototype. It doesn't mean any constructor was invoked. You can achieve the same yourself with Object.create(Object.prototype). Commented Aug 19, 2021 at 20:19

1 Answer 1

1

As @Bergi says, both forms use the same internal mechanism under the hood.

First, an object literal inside a JS script is not JSON, it is an "object initializer":

// object initializer, NOT JSON
let myPet = {
    species: 'Dog',
    ageMs: 1000 * 60 * 60 * 24 * 365.24 * 5 // ~5 years, in millis
}

While no constructor is explicitly invoked by the literal notation, it's also not the case that the created object is just the literal properties; the JS engine still does some setup work. I've never dug into this before, but it appears that the spec calls that setup work "OrdinaryObjectCreate".

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

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.