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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With