Why is null instanceof Object false? | SoloLearn: Learn to code for FREE!


Why is null instanceof Object false?

https://www.sololearn.com/post/103649/?ref=app The question is explained in the post above.

5/25/2019 10:01:05 AM


4 Answers

New Answer


1/2 I don't know the exact answer but let me try. null is actually a primitive value but typeof null returns "object" because of a bug since the creation of JS. null is often used to signify an empty reference to an object. https://stackoverflow.com/questions/20480729/why-does-typeofnull-return-object-but-you-cant-assign-properties-to-it The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof So my guess is that null's prototype(if it exists) don't have Object constructor in its prototype chain & thus it returns false. Eg. // constructors function C1(p) { this.p = p; } function C2(p) { this.p = p; } // objects/instances const o1 = new C1(20); console.log(o1 instanceof C1); //-> true console.log(o1 instanceof C2); //-> false console.log(o1 instanceof Object); //-> true const o2 = new C2(40); console.log(o2 instanceof C2); // -> true


Thank you guys, I finally got my answer. It's just bcoz, null have no constructor. Or if further saying, null has none properties.


2/2 (continued) console.log(o2 instanceof C1); //-> false console.log(o2 instanceof Object); //-> true


AFAIK instance of null is undefined 🤔