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

45,124

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.

Share:
45,124
Matthew Layton
Author by

Matthew Layton

Passionate about programming, technology and DLT.

Updated on May 29, 2020

Comments

  • Matthew Layton
    Matthew Layton almost 4 years

    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?

  • jpaugh
    jpaugh over 6 years
    Thanks for the doc link; but instanceof is just as pertinent: "The instanceof operator tests presence of constructor.prototype in object's prototype chain."
  • Ninja Coding
    Ninja Coding about 6 years
    excuse me, could you explain why?
  • Artur Udod
    Artur Udod about 6 years
    @NinjaCoding basically you can check the link provided at the start of the question stackoverflow.com/questions/203739/…. You'll find a more detailed explanation. But essentially String objects are not primitives, that's the thing. Welcome to js =)
  • Hashbrown
    Hashbrown almost 6 years
    well that's not gonna work if it actually is a String ((function() { return typeof this; }).call('foo'): object), this'll work for both
  • user227353
    user227353 over 2 years
    @NinjaCoding because this answers the first question "So how do you find the type or "instanceof" a string literal?"