1

var name = new String("green");
    console.log(name instanceof String);//returns false
    var color= new String("green");
    console.log(color instanceof String);//returns true

Here the first one is returning false and the second one is returning true,what is the reason if i use variable as name it showing false and are there are any variables like name which throws error as happened with variable name

prasanth
  • 22,145
  • 4
  • 29
  • 53
Abhishek
  • 351
  • 1
  • 3
  • 18

3 Answers3

2

Since name is reserved keywrd in javascript (not really reserved but global object), it directly points to window.name

you can try _name and it will work

var _name = new String("green");
console.log(_name instanceof String);//returns true
Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
1

This is because you are trying to overwrite the global name variable, which has a setter that automatically converts anything you assign to it to a string (new String creates a String object, which is not the same as a string).

The solution: use a different variable name or properly scope your variables.

console.log(typeof name); // string

var name = new String("green");

console.log(typeof name); // still string

var color = new String("green");

console.log(typeof color); // object

// create new scope
function myFunction() {
  var name = new String("green");

  console.log(typeof name); // object

  var color = new String("green");

  console.log(typeof color); // object
}

myFunction();
JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

In the first case it checks the prototype chain find it undefined and return false. This is not only with name but following example will also return false

var simpleStr = 'This is a simple string'; 
console.log(simpleStr instanceof String);

An alternative way is to test it using typeof or constructor The same example will return true for the following case

var simpleStr = 'This is a simple string'; 
simpleStr .constructor == String

For your example also if you do

var name = new String("green");
name .constructor == String

it will return true

brk
  • 48,835
  • 10
  • 56
  • 78
  • This question isn't a problem with OP's understanding of the `instanceof ` operator. OP is asking why it behaves differently on two variables that have both had `new String('...')` assigned to them. – JLRishe Feb 13 '17 at 05:39