Please what does mean this:
if (a && b == c){};
I did not understand the logic of the condition statement
&&
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With