Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please what does mean this : if (a && b == c){};?

Please what does mean this:

if (a && b == c){};

I did not understand the logic of the condition statement

like image 213
Nicholas DiPiazza Avatar asked Jan 01 '23 04:01

Nicholas DiPiazza


2 Answers

&& has lower precedence than ==, so it's equivalent to:

if (a && (b == c))

It means if a has a truthy value and also the value of b is equal to the value of c.

like image 77
Barmar Avatar answered Jan 03 '23 18:01

Barmar


The condition (a && b == c) has two operators. The Logical AND Operator and the Equality Operator.

The operation foo && bar returns true, if both operands foo and bar have truthy values.

foo == bar returns true, if foo equals bar.

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

If an expression contains more than one operator, the operator precedence is of the utmost importance.

Operator precedence determines the way in which operators are parsed with respect to each other. Operators with higher precedence become the operands of operators with lower precedence.

The == operator has a higher prededence than the && operator. Therefor the above condition will check b == c first. If the result is true and the value of a is truthy, the result of the condition will be true.

The Grouping operator ( ) has the highest precedence and therefor can be used to force a specific order of operations.

If you're not absolutely sure in which order operations will be processed, use the grouping operator!

The result of

(a && (b == c)) 

will be the same as the result of

(a && b == c)

but is better readable. Of course you should learn and know the precedence of operators. But if in doubt and especially in a really hairy line with lots of operators, the value that a few brackets add to readability can easlily outperform the costs of a few bits of additional code.

like image 26
Olafant Avatar answered Jan 03 '23 16:01

Olafant