0

In the following code, if typeof of something and arbit comes out to be string, why doesn't instanceof String return true:

const roles = ['something', 'arbit'];
console.log("Array.isArray(roles):", Array.isArray(roles));
console.log("roles instanceof Array:", (roles instanceof Array));
roles.forEach(element => {
    console.log(`[${element}]`);
    console.log(`\ttypeof(${element}):`, typeof(element));
    console.log(`\t${element} instanceof String:`, (element instanceof String));
});

The output for this is:

Array.isArray(roles): true
roles instanceof Array: true
[something]
        typeof(something): string
        something instanceof String: false
[arbit]
        typeof(arbit): string
        arbit instanceof String: false

Also, roles instanceof Array evaluates to true. Thoroughly confused.

This is plain JavaScript running in Nodejs 12, though I doubt that makes any difference...

markvgti
  • 4,321
  • 7
  • 40
  • 62
  • This might be helpful, https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used – JazzBrotha Jan 30 '20 at 06:41
  • @FoggyDay What does this have to do with Typescript, I'm using pure JavaScript. Did I miss something? – markvgti Jan 30 '20 at 06:49
  • @JazzBrotha That was helpful, thanks! – markvgti Jan 30 '20 at 06:52
  • Helpful, but the real issue is "String" vs. "string". See [Evert's](https://stackoverflow.com/a/59980364/3135317) reply and [this](https://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string) thread. – FoggyDay Jan 30 '20 at 16:09

2 Answers2

2

Javascript has two main ways to make strings, as a literal:

const foo = "hi";

and via the string constructor

const bar = new String("hi");

These are not the same thing. The second one will be a bit slower and have subtle behavior differences.

So the reason instanceof String doesn't work, is because your literal string is not an instance of this class.

Generally you'll want to avoid new String().

Evert
  • 93,428
  • 18
  • 118
  • 189
  • This is the correct answer. It's also discussed in [this](https://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string) thread. – FoggyDay Jan 30 '20 at 16:04
2

Use typeof element === "string" instead of instanceof. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof instanceof doesn't work with primitive data types.