It means stopping code execution as soon as possible depending on the value.
Logical operators like &&
and ||
can be used to control program flow directly using the concept of short circuit evaluation.
AND &&
Rule: Return the first false operand, otherwise return the last true operand.
Example
console.log(3 === 3 && 'a' === 'a'); // Output: true
console.log(3 === 3 && 'cow'); // Output: cow
In the second line, it did not return true
.
The way it works is that the operator will return the last value if all the previous values are truthy.
Example
console.log(3 === 3 && 'cow' && 'chicken'); // Output: chicken
console.log(3 === 3 && false && 'chicken'); // Output: false
If any of the operands are falsey the first falsey operand is returned. And any operants that follow aren’t considered.
Morphing the previous example, we can use short circuiting to run code only if a condition is true, in one concise line of code.
3 === 3 && `cow` && console.log('chicken'); // Output: chicken
OR ||
Rule: Return the first true operand, otherwise return the last false operand.
console.log(3 === 3 || 'cow' || 'chicken'); // Output: true
console.log(3 === 4 || 'cow' || 'chicken'); // Output: cow
console.log(3 === 4 || false || 0); // Output: 0
If all operands are falsy, the last value is returned.
A More Concise Code
Simple if statment function example.
function isAdult(age) {
if (age && age >= 18) {
return true;
} else {
return false;
}
}
This can become much more concise using short circuiting.
function isAdult(age) {
return age && age >= 18;
}
Default Values
var x = x || 1;
Make use of short circuiting to assign a default value if there isn’t one.
function countToFive(start) {
start = start || 1;
for(var i = start; i <= 5; i += 1) {
console.log(i);
}
}
However there is a problem. What if we want to start at zero?
If we pass this in, it will be falsey. And one will be assigned to starts. So it’s impossible to start the count at zero. This is why you have to be careful when you use the or operator to assign a default value.
The recommended way to assign a value according to ES2015 is to assign a value the parameter in the function declaration.
function countToFive(start = 1) {
for(var i = start; i <= 5; i += 1) {
console.log(i);
}
}
Important Note
Short circuit evaluation is not as good as replicating if else
. You’ll want to reserve its use to times when it’s very easy to tell what your code is trying to accomplish – as if statements are usually much easier to read and understand.