Why is there a constructor property on every js object?

I always wanted to ask this question but was hesitant because I thought it might make me look like an idiot! Away I searched SO, but the answers were vague. MDN doesn't provide any useful hint either😑
Every JS object has a constructor property (i.e, Object.prototype.constructor); I mean what does it do? what is its purpose? Is it a remnant from pre ECMA days of JavaScript?
Thinking about it in the context of a class makes sense but outside that it isn't very sensible.

Did you already run into this page on MDN? I've found that one to be very enlightening.

All the constructor property does is a link to the function that constructed that object. It's not a commonly used property, but it's there, and it has its occasional use case (apparently - I haven't yet had a use for it).

It still makes sense outside of a class. In this code example:

function MyThing() { ... }
const obj = new MyThing()
console.log(obj.constructor) // MyThing

The thing that constructed "obj" was the function MyThing. MyThing is a constructor, just as much as the "constructor" function in class { constructor() { ... } } is a constructor. Remember that typeof (class {}) === 'function' - the class object itself is literally the constructor function that was defined within - everything else has just been attached to that constructor in one way or another. It's no different with the "MyThing" function.

The constructor property even makes sense on object literals, as each object literal is implicitly being constructed by the "Object" constructor. It makes sense for primitives as well - when I do 'test'.constructor, the engine is auto-magically wrapping my primitive in an instance of a String class so that I'm able to access properties like "slice" or "constructor". And what did the engine use to construct that string wrapper? Why, the String constructor! So it makes sense that 'test'.constructor === String

As for some possible use cases, I'll refer you to the MDN article that I linked to, which does a good job of explaining a couple involving inheritance.

Does that help explain it at all? Or do you have some more specific confusion points around it?


Ah! I get it, so it's a back reference to the parent class of an object.
That's all I needed!
I was looking for a possible use case of this property. I guess I found just that (as mentioned).
Thanks @theScottyJam :blush:

1 Like