Photo by Vasily Koloda from unsplash. It could be me walking through JS :)
Much of the content is based from this tutorial. It helps me put it in writing to remember!
|| OR
If any of its arguments is true
then it returns true
. Otherwise, it returns false
. When combining 2 operands, there are 4 possible combinations:
alert( true || true ); // true
alert( false || true ); // true
alert( true || false ); // true
alert( false || false ); // false
If the operand is not a boolean, it is converted to a boolean (truthy
or falsey
), like:
if (1 || 0) { // works just like if( true || false )
alert( 'truthy!' );
}
|| OR to find the first truthy value
You can use || OR
to find the first truthy value if you have several operands. From what I read, what follows is a feature from Javascript.
- It evaluates operands from left to right.
- It converts each of them to boolean, and returns the first one being
true
. - If it reaches the end and it has not found any
true
(all werefalse
), it returns the last operand.
alert( 1 || 0 ); // 1 (1 is truthy)
alert( null || 1 ); // 1 (1 is the first truthy value)
alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
You can use the || OR
to do short-circuit evaluation
: all operands will be evaluated until the first truthy
is found, and that value is returned without reaching the following ones. For instance:
true || alert("not printed");
false || alert("printed");
Will print the second message only because, in the first one, evaluation stops upon reaching the first operand, which is true
.
&& AND
true
is returned if both operands are true
. Otherwise, false
is returned:
alert( true && true ); // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false
Like in || OR
, operands are evaluated as booleans:
if (1 && 0) { // evaluated as true && false
alert( "won't work, because the result is falsy" );
}
&& AND to find the first falsy value
Same as with || OR
, multiple operands can be evaluated and this time &&
helps you find the first falsy value:
- It evaluates from left to right.
- It converts each operand to boolean, and when it finds the first
false
it stops and returns its value. - If it reaches the end of the operands and all of them are
truthy
, it returns the last one.
// if the first operand is truthy,
// AND returns the second operand:
alert( 1 && 0 ); // 0
alert( 1 && 5 ); // 5
// if the first operand is falsy,
// AND returns it. The second operand is ignored
alert( null && 5 ); // null
alert( 0 && "no matter what" ); // 0
&& AND
takes precedence over || OR
, so a && b || c && d
is the same as if the &&
were in parenthesis: (a && b) || (c && d)
.