Why does JSLint tell me to use “=== undefined” instead of “typeof … === 'undefined'”?

被刻印的时光 ゝ 提交于 2019-12-03 23:51:39

问题


I coded the following:

showTitles = (typeof showTitles !== 'undefined') ? showTitles : 'Y';
showSelectGroup = (typeof showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';

But JSLint is saying:

Warning 3 JS Lint: Unexpected 'typeof'. Use '===' to compare directly with undefined.

How should I change my code?


回答1:


Note that whether this is best practice in general is debatable, but if you want to make it work with JSLint, you could do this

showTitles = (showTitles !== undefined) ? showTitles : 'Y';



回答2:


Probably by using

showTitles = (showTitles === undefined) ? 'Y' : showTitles;
showSelectGroup = (showSelectGroup === undefined) ? 'Y' : showSelectGroup;

jslint has no issues with that (assuming showTitles and showSelectGroup are declared with var)

However, I'd write it as

var showTitles = showTitles || 'Y';
var showSelectGroup = showSelectGroup || 'Y';



回答3:


This message reflects the latest best practices. As of ES5 strict mode, the global value of undefined can no longer be changed and a direct comparison is simpler code and faster. In short, JSLint is aware of all this, and is giving you good advice.

In this case, change typeof showTitles !== 'undefined' to showTitles === undefined.



来源:https://stackoverflow.com/questions/12628068/why-does-jslint-tell-me-to-use-undefined-instead-of-typeof-undef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!