What are JavaScript short-circuiting operators?

The JavaScript language has a wide range of operators. One of the lesser-used operators is the short-circuiting operators. This operator is a binary operator that returns the first operand if it is a truthy value, and the second operand if it is a falsy value.

The short-circuiting operators are && for the and operator and || for the or operator. The and operator will return the first operand if it is truthy, and the second operand will be returned if the first operand is falsy. The or operator will return the first operand if it is falsy, and the second operand will be returned if the first operand is truthy.

The short-circuiting operators are often used in if/else statements. For example, if you want to check to see if a value is greater than 10, you can use the following code:

var value = 20;
if (value > 10) {
	console.log("The value is greater than 10");
}else {
	console.log("The value is less than 10");
}

The code above will work as expected, but it can be rewritten using the short-circuiting operators:

var value = 20;
var result = value > 10;
console.log(result);

In the code above, the result variable will be set to the value of the first operand, which is the result of the comparison. If the first operand is falsy, then the second operand will be returned. This can save you a few lines of code, and it can be useful when you want to check a condition quickly.

The short-circuiting operators are also used in for loops. For example, the following code will print the first 10 numbers:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0; i < numbers.length; ++i) {
	console.log(numbers[i]);
}

However, the following code will print the first 5 numbers, because the number 6 will not be printed:

var numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < numbers.length; ++i) {
	console.log(numbers[i]);
}
💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.