How to use JavaScript Logical or (||) operator
In JavaScript, the logical or(||) operator is used to evaluate the expressions from left to right side.
expression 1 || expression 2 (short circuit evaluated)
It returns the first expression, if the value can be converted to true
otherwise, it returns the second expression.
The second expression is short circuit evaluated it means the second expression is executed or evaluated only if the first expression evaluates to false
.
Let’s see an example:
console.log( 1 || 2 ) // 1
In the above example, the output is 1
because 1
is a truthy value.
console.log( 0 || 10) // 10
Here it returns 10
because 0
is a falsy value.
More examples
console.log(false || true ) // true
console.log(false || false) // false
console.log( " " || "hello") // "hello"
console.log(" " || 0 ) // 0