this post's header image

JS: variable && function()

JavaScript is a really weird language.

You may come across a statement such as:

myVariable && myFunction();

Which is equivalent to:

if (myVariable) {
    myFunction()
}

If you look up this syntax online, you'll find this is an "abuse" of the language syntax. && evaluates the thing on the right if the thing on the left is true. If the left side is falsy, it won't execute the right-hand side.

Even though it's legal to use this type of statement, please don't. Our bottleneck as developers is reading speed, not writing speed. Use more lines when it makes the statement easier to read. Don't abuse your language.

Respond to this post and join the conversation on DEV