Short Circuiting (part 1 “||”)

Andrew Park
2 min readMay 30, 2021

The other day, I ran into code that I did not quite understood. And it looked something like below:

The line 13 did not make sense to me. I understood double pipe operator (||) as logical “or” operator that I only used get either “true” or “false” Boolean value:

But it turned out that I can use “||” and “&&” as “Short Circuiting” to return a value or even a function.

For ”||“ it works like this:

In the above example, we have a variable called person with name and age as its property.

The return value of person.name || person.age is “Andrew” since person.name is true. The operation returns the value of first operand (person.name), and it doesn’t event look at the second operand (person.age). For “or” operation, only one operand needs to be true for the entire operation to be true.

The return value of person.gender || person.age is 10 since the first operand (person.gender) is false (it does not exist). For “or” operator, if the first operand is false, it will move on to second operand to complete the operation.

The return value of person.occupation || “Andrew is looking for a job” is string “Andrew is looking for a job”. Since the first operand is false, the operation returned the value of second operand, in this case a string.

The return value of person.weight || (() => person.weight = 150)(), is 150. Once again, since the first operand is false, the operation returned the value of second operand, in this case the return value of a function.

So, go back to the original example, the function I that I had trouble understand could been re-written as below (line 16–22) with an if/else statement.

To me, if/else is easier to read and understand, but for simple operation, using Short Circuiting may work too. On my next blog we will take a look at Short Circuiting using (&&).

--

--