All Articles

Short Circuit Statements

Do You Do This?

There you are writing code. You want to run a function if a certain condition is met. Otherwise, you want your application to do nothing else concerning that function right now. You immediately think of a ternary statement:

isConditionTrue ? myFunction() : null;

Let’s assume that you don’t want to do anything with the isConditionTrue value other than checking that it’s true. That null just doesn’t feel right, does it? You’re not going to touch it ever… there’s just no need for it. What do you do?

Use A Short Circuit Statement!

A short-circuit statement works like this: if the first value evaluates to true or is truthy, then the value following the && will run. If the first value is false or falsy*, then the line will evaluate to the value of the falsy value, and the function will not be executed.*

// if isConditionTrue is true, then execute myFunction
isConditionTrue && myFunction();

What if you want to check if one of two conditions is true? Do this:

const isEitherConditionTrue = isConditionOneTrue || isConditionTwoTrue;

isEitherConditionTrue && myFunction();

Yes, you can also write it inline

isConditionOneTrue || isConditionTwoTrue && myFunction();

but I suggest not doing this, and instead using one more line of code to make each line simpler to read. An underlying idea that I suggest to go beyond is the one where “one-liners” and very terse compact code are more highly prized over simplicity and readability.

But now what if you want to check if BOTH conditions is true? I bet you can guess:

const areBothConditionsTrue = isConditionOneTrue && isConditionTwoTrue;

areBothConditionsTrue && myFunction();

Yes, these are simple examples. But they fit well with the short-circuit statement, which is also meant to be simple.

*Try these examples out in your console:

const myFunc = () => {
    return "function executed"

// these run the function
// let value = true 
// let value = "a string" 
// let value = 10 
// let value = {}
// let value = []

// these return the falsy value
// let value = false 
// let value = 0 
// let value = "" 

value && myFunc()
Published 1 Jul 2018

Typescript Developer - Node/React, Rust enthusiast, jiujitsu player, southern California native