JavaScript Short Circuit Assignment

When building websites or web apps, the data that is shown on the screen is often dynamically created dependent on some user defined input. Sometimes this input is missing or not as expected. In these cases it’s good to have default values to fall back to so that our app doesn’t break or behave unexpectedly.

Below is an example of assigning default values to a variable using the logical OR operator, known as short circuit assignment:

So what’s going on here? To understand, let’s first have a quick look at logical operators.

Logical Operators

AND Operator (&&)

OR Operator (||)

NOT Operator (!)

Logical Operators in if statements

However, what happens when we put non-boolean values in an if statement?

This means that some of these expressions evaluate to true and some of them evaluate to false. In fact all expressions can be evaluated as either true (known as a truthy value) or false (known as a falsy value).

Truthy and Falsey Values

All other values, whether they be strings, numbers or objects (and of course the true boolean value) evaluate to true and are known as truthy values.

Logical Operators and Non-Boolean Values

In the first example, we see that the result of "hello" && "world" is actually "world". This is because an AND operator needs to test the truthiness of both sides of the expression - both values must be true for the whole expression to be true. It then returns the last value that it evaluated, in this case "world" if the expression evaluates to true.

This isn’t quite the same for OR. Since OR only needs one of the values to be true in order for the whole expression to be true, if the first value is truthy then it can exit out of the evaluation early, having only tested the first value, and then return the first value. This is known as short circuit evaluation — if the first value is true, there is no need to check the rest of the expression, so it short circuits having only tested the first value.

However, if the first value does evaluate to false, then the OR statement must then check the second value to see if that is true.

In this case, 0 evaluates to false, so the OR statement then has to check the truthiness of the second value - 1 is truthy, so 1 is returned from the expression.

In this way we can assign default values. We can use a user-defined variable as the first value and a default to fall back to as the second value. If the user gives a truthy input, their input is returned because the OR statement short circuits. In the case that the user gives no input, the first variable will be falsy and so the second value is returned.

const userVariable = "user value"; 
const value = userVariable || "default value";
const userVariable = "";
const value = userVariable || "default value";

I hope that you’ve found this post useful. Please let me know your comments/questions through Twitter.

Originally published at