How to "instanceof" a primitive string (string literal) in JavaScript [duplicate]
In JavaScript, I can declare a string in the following ways;
var a = "Hello World";
var b = new String("Hello World");
but a is not an instance of String...
console.log(a instanceof String); //false;
console.log(b instanceof String); //true;
So how do you find the type or "instanceof
" a string literal?
Can JavaScript be forced to create a new String()
for every string literal?
Solution 1:
use typeof "foo" === "string"
instead of instanceof.
Solution 2:
Use typeof
instead and just compare the resulting string. See docs for details.
Solution 3:
There is no need to write new String()
to create a new string. When we write var x = 'test';
statement, it create the x
as a string from a primitive data type. We can't attach the custom properties to this x
as we do with object literal. ie. x.custom = 'abc';
x.custom
will give undefined value. Thus as per our need we need to create the object. new String()
will create an object with typeof()
Object and not string. We can add custom properties to this object.