user6568810
user6568810

Reputation:

What is the execution order of if condition in JS

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 :)

Upvotes: 2

Views: 2802

Answers (5)

Inod Umayanga
Inod Umayanga

Reputation: 182

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

Upvotes: 0

King Henry
King Henry

Reputation: 416

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.

Upvotes: 6

th3n3wguy
th3n3wguy

Reputation: 3747

Yes. If the first condition fails, then the rest of the checks won't work because of the short circuit functionality in JavaScript.

Upvotes: 2

Terry Lennox
Terry Lennox

Reputation: 30705

It will return immediately, it won't throw an error if arr[0] is null.

Upvotes: -1

messerbill
messerbill

Reputation: 5639

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

Upvotes: 0

Related Questions