Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, where does the "constructor" property come from, in an object that is supposed to be empty?

The following snippet of code is taken from Eloquent JavaScript.

var noCatsAtAll = {};
if ("constructor" in noCatsAtAll)
  console.log("Yes, there definitely is a cat called 'constructor'.");

I find it quite mystifying. Why is the if condition true?

like image 560
deltanovember Avatar asked Jan 18 '26 04:01

deltanovember


2 Answers

JavaScript objects have a function called constructor which is the function that created the object's instance. It's built-in to all objects. The in operator tests for the presence of something called "constructor" in the instance of your dictionary, so it returns true. The same thing would happen if you tested for length, for example.

like image 149
kprobst Avatar answered Jan 19 '26 18:01

kprobst


All instances of Object have a constructor property that specifies the function that constructs the Object's prototype.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object#Properties_2

The in operator looks at all properties, including inherited ones. If you only want to see the properties on the object itself, you can use hasOwnProperty:

var a = {};
"constructor" in a; // true
a.hasOwnProperty("constructor"); // false

Note that while the in operator sees "constructor", a for (key in a) loop wouldn't. This is because the "constructor" property is non-enumerable.

like image 34
Tikhon Jelvis Avatar answered Jan 19 '26 18:01

Tikhon Jelvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!