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

Matthew Layton picture Matthew Layton · May 28, 2013 · Viewed 38.1k times · Source

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?

Answer

Artur Udod picture Artur Udod · May 28, 2013

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