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

JavascriptStringInstanceofString Literals

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Use typeof instead and just compare the resulting string. See docs for details.

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew LaytonView Question on Stackoverflow
Solution 1 - JavascriptArtur UdodView Answer on Stackoverflow
Solution 2 - Javascriptisaach1000View Answer on Stackoverflow
Solution 3 - JavascriptVishnudas TekaleView Answer on Stackoverflow