Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does instanceof return false for some literals?

"foo" instanceof String //=> false "foo" instanceof Object //=> false  true instanceof Boolean //=> false true instanceof Object //=> false false instanceof Boolean //=> false false instanceof Object //=> false  12.21 instanceof Number //=> false /foo/ instanceof RegExp //=> true  // the tests against Object really don't make sense 

Array literals and Object literals match...

[0,1] instanceof Array //=> true {0:1} instanceof Object //=> true 

Why don't all of them? Or, why don't they all not?
And, what are they an instance of, then?

It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.

like image 425
Jonathan Lonowski Avatar asked Oct 15 '08 04:10

Jonathan Lonowski


People also ask

Why does instanceof return false?

Using the instanceof Operator When an Object Is nullIf we use the instanceof operator on any object that's null, it returns false. We also don't need a null check when using an instanceof operator.

What does Instanceof return in JavaScript?

The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.

How does Instanceof Work difference with Typeof?

typeof: Per the MDN docmentation, typeof is a unary operator that returns a string indicating the type of the unevaluated operand. instanceof: is a binary operator, accepting an object and a constructor. It returns a boolean indicating whether or not the object has the given constructor in its prototype chain.

Is array an object Instanceof?

Short answer: Array instanceof Object is true because functions are objects and every object has Object.


1 Answers

Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:

var color1 = new String("green"); color1 instanceof String; // returns true var color2 = "coral"; color2 instanceof String; // returns false (color2 is not a String object) 

I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use typeof "foo" === "string" instead of instanceof.

An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.

like image 81
John Millikin Avatar answered Oct 10 '22 21:10

John Millikin