Eugene Beliaev
Eugene Beliaev

Reputation: 881

Understanding of instanceof operator

I found very strange thing about performing "instanceof" on primitive objects like strings, numbers, booleans, etc. Explain please anybody this code:

var str = 'A string';
var num = 1;
var bool = true;

str  instanceof str.constructor; // returns false
num  instanceof num.constructor; // returns false
bool instanceof bool.constructor; // returns false

Upvotes: 1

Views: 49

Answers (2)

wiredolphin
wiredolphin

Reputation: 1641

As of the definition given by MDN:

The instanceof operator tests presence of constructor.prototype in object's prototype chain.

If you want to call the constructor use the new operator. Try like so:

var str = new String('A string');

Upvotes: 1

Maxim Goncharuk
Maxim Goncharuk

Reputation: 1333

instanceof operator tests only object. You try to test primitives, so it returns false. More here

Upvotes: 1

Related Questions