Rd2
Rd2

Reputation: 157

Why does this sentence, return false, when asked if it is a string?

Sorry if this question sounds basic, but I can't find an answer to it online. When I asked the console, if this string is a String, it says false. Why?

"i am a string" === String; //outputs: false

var x = "i am a string"; 
x === String; //outputs: false

x != String; //outputs: true 

This is the real reason I went into the console.

var myWonderfulArray = ["one", "two", 4,6, "five"];
function someFunction(element){
    return element === string;
}
myWonderfulArray.some(someFunction);

and it outputs this errror: uncaught ReferenceError: string is not defined

I don't understand at all! Because it is actually a string, like there are strings in there.

Upvotes: 1

Views: 119

Answers (2)

Shan Surat
Shan Surat

Reputation: 304

You use comparison operators (==, ===, !=, !==, <, >, <=, >=) when you want to compare values. If you want to check if a variable is a string, use the typeof operator.

Ex:

typeof "i am a string" == 'string'    //outputs: true

var x = "i am a string"; 
typeof x === 'string'               //outputs: true

typeof x != 'string'               //outputs: false

You can learn more about comparison operators here, and the typeof operator here.

Upvotes: 0

Dai
Dai

Reputation: 155065

  • x === String means "is x exactly equal to the String-prototype-constructor-function", which it isn't.

  • To compare types in JavaScript, use the typeof operator.

    • JavaScript has only a few fundamental data-types:
      • string
      • number
      • object (this is also the type of null values)
      • undefined
      • boolean
      • bigint
      • symbol
      • function
    • Note that the typeof operator always returns a string value with the name of the (fundamental, or intrinsic) type.
      • The symbol type was added to JavaScript only very recently, which is why typeof returns a string instead of a symbol value - in case you're wondering.
  • Don't confuse JavaScript types with Object prototypes. You cannot use typeof to determine an object's prototype - you need to use instanceof for that, but instanceof is not reliable because JavaScript does not use nominal typing (this is why TypeScript has type-guard functions to assert structural types).

Your code should look like this:

typeof "i am a string" === 'string'; //outputs: true

var x = "i am a string"; 
typeof x === 'string'; //outputs: true

Upvotes: 4

Related Questions