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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744679984a4587559.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信