Search code examples
javascriptstringinstanceofstring-literals

How to "instanceof" a primitive string (string literal) in JavaScript


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

  • use typeof "foo" === "string" instead of instanceof.