blog

Replacing simple conditionals with logical AND (&&)

In JavaScript I often replace this:

if (simpleStatement) {
doAThing();
}

with this:

simpleStatement && doAThing();

What the second example does is take advantage of short-circuit evaluation. If simpleStatement is truthy it will execute doAThing function, if it’s falsy it would return false and proceed to the next line in code.

Using if conditional is probably easier to follow for a bigger number of people and there is rarely ever the need to choose code-golfing/simple/slick syntax over the most basic one but this one I love too much to let go.

I don’t use this synatx when simpleStatement is not a simple truthy/falsy evaluation but instead includes equality (===) or multiple chained statements. When if block would contain more than a single line function call or when there is a need for if else statement I would also opt-out from this approach.