0

Why we shouldn’t use “new String()” in JavaScript?

Reading Time: 1 minute

Here is why we shouldn’t use “new String()” while creating variable of string.


var foo = new String("A");

var baz = new String("A");

console.log(foo == baz);//false

console.log(foo === baz);//false

 

whereas if notice the below code

var foo = String("A");//var foo = "A";

var baz = String("A");//var baz = "A";

console.log(foo == baz);//true

console.log(foo === baz);//true

 

if you create any variable with “new” keyword it would be considered as object in JavaScript & both objects when compared with == or === it’s not same. So now we know why primitive types are created like var foo = “A”;

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.