Weird output of instanceof in javascript

when i do next 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 use name as a variable that shows me false giving it some other variable 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.

+3


source to share


3 answers


This is because it is name

not a variable, it is a property in an object window

. When you try to create a named global variable name

, it will be ignored and the existing property will be used instead.

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



typeof name

will return "string"

instead of "object"

. Since it is not an object, it is not an instance of the class String

.

+1


source


I just wrote and run a little snippet

function test(){
    window.name = 'Hello World';
    alert(name);
}

      

If you try it, you will see that it prints out "Hello World", so your problem is caused by the scope of the variable .
When you call console.log(name instanceof String)

, you actually doconsole.log(window.name instanceof String);




Also, window.name is a primitive string , not an object, so to check if it is a string try something like this:

alert(typeof name === "string" );

      

And he will deduce 'true'

!

0


source


The previous answers don't seem to emphasize that this is a special case . This is not only because the global object window

already has a name parameter, but because window.name (= equivalent to global name

in the browser environment) is treated as a special case, i.e. always inserted into a primitive string.

Other properties defined in the global window object do not have this behavior, you can try adding the property yourself:

window.xyz = "primitive";
window.xyz = new String("NewDelhi");
window.xyz;
> String {0: "N", 1: "e", 2: "w", 3: "D", 4: "e", 5: "l", 6: "h", 7: "i", length: 8, [[PrimitiveValue]]: "NewDelhi"}

      

The reason it is treated as such is because the original semantics of the property can be preserved: it is the name of the window, nothing but a primitive string makes no sense.

See this discussion for more details (which may even require this question to be repeated as a duplicate).

0


source







All Articles