Bhesh Gurung
Bhesh Gurung

Reputation: 51030

In Javascript is checking for the type only using typeof operator bad?

I see there are a whole lot of different ways to check the typeof a var in Javascript.

But using the typeof of operator seems pretty simpler than other ways - e.g.

if(typeof someVar == typeof "")

if(typeof someVar == typeof [])


function myFunc() {}

if(typeof someVar == typeof myFunc)

Is it even valid or a really bad practice to do that? Why?

Thank you.

Upvotes: 3

Views: 3487

Answers (3)

typeof is perfectly fine to use, but not for general type checking. That's not its purpose.

typeof [] == "object"

It can only distinguish between "object", "function", "undefined" and the primitives "boolean", "number" and "string". For more advance type checking, you need to use instanceof or more complicated checks.

[] instanceof Array // works reliably only if there's a single frame
toString.call([]) == "[object Array]" // always works, but only with some types.

Upvotes: 4

Ruan Mendes
Ruan Mendes

Reputation: 92274

One of the main problems of typeof, is that it won't return "string", "boolean", "number" if you create those objects using their constructors. Look at this example testing for strings

typeof "my-string" // "string"
typeof String('my-string') // 'string'
typeof new String("my-string") // "object".

Therefore, when testing whether an argument or variable is a string, boolean, number, you need to use Object.prototype.toString which returns consistent results

function isString(obj) {
   return Object.prototype.toString.call(obj) == "[object String]";
}

Upvotes: 3

Norman Joyner
Norman Joyner

Reputation: 955

If you need to check if both the values and types are the same you can use the === comparison operator; however, if you just need to check the type it would be most appropriate to use instanceof.

Upvotes: 0

Related Questions