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

javascript - What is the execution order of if condition in JS - Stack Overflow

programmeradmin3浏览0评论

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, or undefined? what is wtith the value? what type is it? toString and gaetting an empty string requires an empty string. why toString? – Nina Scholz Commented Mar 5, 2018 at 15:33
Add a ment  | 

5 Answers 5

Reset to default 6

It 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.

发布评论

评论列表(0)

  1. 暂无评论