Skip to content
Advertisement

Two conditions in one if statement does the second matter if the first is false?

Okay, so I have this piece of code tested and I found there isn’t any exception thrown out.

JavaScript

Does the statement here

JavaScript

mean that if the first condition is false we don’t even have to check the second condition?

Or it equals to

JavaScript

?

And, what if it is written in C or python or some other languages?

Thanks

Advertisement

Answer

It is common for languages (Java and Python are among them) to evaluate the first argument of a logical AND and finish evaluation of the statement if the first argument is false. This is because:

From The Order of Evaluation of Logic Operators,

When Java evaluates the expression d = b && c;, it first checks whether b is true. Here b is false, so b && c must be false regardless of whether c is or is not true, so Java doesn’t bother checking the value of c.

This is known as short-circuit evaluation, and is also referred to in the Java docs.

It is common to see list.count > 0 && list[0] == "Something" to check a list element, if it exists.


It is also worth mentioning that if (list.length>2 && list[3] == 2) is not equal to the second case

JavaScript

if there is an else afterwards. The else will apply only to the if statement to which it is attached.

To demonstrate this gotcha:

JavaScript

will work as expected, but

JavaScript

will also tell any Human who isn’t Jordan they are not human.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement