英文:
Which is the better way to check undefined in Javascript?
问题
我之前一直像这样检查 `undefined` 值:
if(variable !== 'undefined')
然后我遇到了下面的代码:
if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')
我采用了相同的约定,因为我知道当变量未声明时这样更安全。但在我的代码审查中,有人指出我可以简单地写成:
if(variable1 || variable2)
这些方式中哪一个是最标准的检查 `undefined` 的方式?
英文:
I had been checking for undefined
values myself like:
if(variable !== 'undefined')
then I came across the following code:
if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')
I followed the same convention knowing it's safer when variable goes undeclared. While in my code reviews, it was pointed I could simple write:
if(variable1 || variable2)
Which of these is the most standard way to check undefined
?
答案1
得分: 2
有以下各种用例
-
if (variable)
是在JavaScript中检查任何变量的真实性的标准方式。您可以在Truthy | MDN Web Docs中找到哪些值将是真实的示例。另请参考Falsy | MDN Docs。 -
明确检查未定义的情况是当变量已声明但未分配值或明确分配了
undefined
时。在这种情况下,请使用if (variable !== undefined)
。 -
如果您从API接收响应,该响应可能包含字符串化的
undefined
值,您可以确定,那么只需执行检查if (variable !== 'undefined')
。
英文:
There are various use case as following
-
if (variable)
is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN Docs -
The cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned
undefined
.
In that case useif (variable !== undefined)
. -
If you are receiving response from an API which might consist of stringified value of
undefined
, which you are sure of, then only do the checkif (variable !== 'undefined')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论