admin管理员组文章数量:1389897
Given:
if(arr[0]!=null && arr[0].value.toString()!="") {
//do something
}
Does an if conditional statement return false immediately after the first statement fails? Or does it check the second condition regardless?
Cheers, Gavin :)
Given:
if(arr[0]!=null && arr[0].value.toString()!="") {
//do something
}
Does an if conditional statement return false immediately after the first statement fails? Or does it check the second condition regardless?
Cheers, Gavin :)
Share Improve this question asked Mar 5, 2018 at 15:27 user6568810user6568810 4- Logical_Operators – palaѕн Commented Mar 5, 2018 at 15:29
- 2 Boolean expressions are short-circuited. – axiac Commented Mar 5, 2018 at 15:31
-
There's already useful answers. But just a ment to help in the future - it's very mon when programming in javascript to use this short-circuiting for using an element only if it exists. Example
{elem && <p>{elem}</p>}
– vapurrmaid Commented Mar 5, 2018 at 15:33 -
maybe some more information is necessary, what is the usual content of
arr[0]
? could it be empty,null
, orundefined
? what is wtith the value? what type is it?toString
and gaetting an empty string requires an empty string. whytoString
? – Nina Scholz Commented Mar 5, 2018 at 15:33
5 Answers
Reset to default 6It depends. If you are checking values with AND (&&
) and the first value is false
, the condition would immediately evaluate to false
because every condition has to evaluate to true
.
If you are checking values with OR (||
) and the first condition is false
, the if statement would check every other condition until it finds a true
value.
Yes. If the first condition fails, then the rest of the checks won't work because of the short circuit functionality in JavaScript.
(arr[0]!=null && arr[0].value.toString()!="")
will directly return false when the first
condition is false because you have used &&
- while (arr[0]!=null || arr[0].value.toString()!="")
would also evaluate the second condition after the first was false.
`if(arr[0]!=null && arr[0].value.toString()!="") {
//do something
}`
It is important to note this statement will be evaluated from left to right. Interpreter will evaluate fist condition and if fist value in array is null condition will be short circuit and jump out of the if block.
It will return immediately, it won't throw an error if arr[0] is null.
本文标签: javascriptWhat is the execution order of if condition in JSStack Overflow
版权声明:本文标题:javascript - What is the execution order of if condition in JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744611926a2615709.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论