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

javascript - typeof a == 'undefined' vs typeof a === 'undefined' - Stack Overflow

programmeradmin3浏览0评论

As I understand the prefered way to check undefined variables is typeof a === 'undefined'.

But why it is better then typeof a == 'undefined'? In which places can it fail?

As I understand the prefered way to check undefined variables is typeof a === 'undefined'.

But why it is better then typeof a == 'undefined'? In which places can it fail?

Share Improve this question asked Apr 22, 2013 at 11:14 Paul AnnekovPaul Annekov 3,2733 gold badges22 silver badges31 bronze badges 1
  • 1 @Jake1164 why it's duplicate? There is parision with "null" in that question. – Paul Annekov Commented Apr 22, 2013 at 11:20
Add a ment  | 

4 Answers 4

Reset to default 10

In this instance, since typeof will always give you a string: It isn't better (nor is it worse). It makes no practical difference.

In general, using === is preferred because it forces you to be explicit about your types and saves you from getting results you don't expect when JavaScript's type resolution rules are unintuitive.

The difference between == and === is that == performs conversions. So for instance 1 will be == to '1' but not === to '1'. The reason why that approach is preferred when you check for undefined is because in JavaScript there are known parison pitfalls.

The most mon:

''        ==   '0'           //false
0         ==   ''            //true
0         ==   '0'           //true
false     ==   'false'       //false
false     ==   '0'           //true
false     ==   undefined     //false
false     ==   null          //false
null      ==   undefined     //true
" \t\r\n" ==   0             //true

So with === you are avoiding the null == undefined problem, which can lead to hard-to-find bugs. That's why you should use == instead of ===. Because === is not performing any conversions behind the scenes, it is also a faster operation.

In this specific case, it won't make a difference effect-wise. Whether you use typeof a == 'undefined' or typeof a === 'undefined' the output will be the same, with no bugs. That's because typeof returns a string. However, the operation will be faster, so you have a negligible performance increase.

Because typeof will only return string, so it is safe to pare two strings with ==.

There is a big difference between == and === (Check out here)

But, since typeof will always return string, it's ok to use this.

发布评论

评论列表(0)

  1. 暂无评论