最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Aug 17, 2011 at 0:53 Bhesh Gurung asked Aug 16, 2011 at 23:38 Bhesh GurungBhesh Gurung 51k23 gold badges95 silver badges143 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 plicated checks.

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

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]";
}

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

发布评论

评论列表(0)

  1. 暂无评论