Short-Circuit Evaluation
Logical And (&&)
It returns the first falsy value. If there is no falsy value, it returns the last value.
console.log(true && null && 1); // null
console.log(true && 'a' && 1); // 1
Logical Or (||)
It returns the first truthy value. If there is no truthy value, it returns the last value.
console.log(false || 'hi' || undefined); // hi
console.log(false || 0 || null); // null
Use
Please look at the example below.
function add(a, b) {
return a + b;
}
console.log(true && add(1, 2)); // 3
console.log(false && add(1, 2)); // false
console.log(true || add(1, 2)); // true
console.log(false || add(1, 2)); // 3
In some cases, 'add' function was called to get the data.
Isn't it similar to a 'if' statement?
Below is a more practical example where things in front of the operators can be changed.