Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird output by instanceof in javascript

when I am doing the following snippet

var name = new String("NewDelhi");
var count = new Number(10);
console.log(name instanceof String); //false
console.log(count instanceof Number); //true

when I am using name as variable it showing me false while giving it some other variable it showing true

var str = new String("NewDelhi");
var count = new Number(10);
console.log(str instanceof String); //true
console.log(count instanceof Number); //true

why is this happening.

like image 310
jayD Avatar asked Jan 27 '26 01:01

jayD


1 Answers

That's because name is not a variable, it's a property in the window object. When you try to create a global variable named name, that will be ignored and the existing property will be used instead.

The type of the property is a string primitive, not a string object. The type of a variable is dynamic, so it could both hold a string primitive or a String object, but the property has a specific type and can only hold a string primitive.

typeof name will return "string", not "object". As it's not an object, it's not an instance of the String class.

like image 181
Guffa Avatar answered Jan 29 '26 14:01

Guffa



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!