DEV Community

Cover image for JS: variable && function()
Winston Puckett
Winston Puckett

Posted on

JS: variable && function()

JavaScript is a really weird language.

You may come across a statement such as:

myVariable && myFunction();
Enter fullscreen mode Exit fullscreen mode

Which is equivalent to:

if (myVariable) {
    myFunction()
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (5)

Collapse
 
robertotonino profile image
Roberto Tonino

Totally agree. Let’s let this kind of things to minifiers.

Collapse
 
kvnls profile image
KVNLS

You can use Optional chaining:
myFunction?.();

developer.mozilla.org/en-US/docs/W...

Collapse
 
winstonpuckett profile image
Winston Puckett

I didn't know they had optional chaining in JS! Thank you!

Collapse
 
mfurkankaya profile image
Furkan KAYA

I think it's pretty readable and understandable. Also people don't know so many things, shouldn't we use those things?

Collapse
 
winstonpuckett profile image
Winston Puckett

The difference for me is the "abuse" of the language part. It seems like this isn't a language feature, but something that happened by accident.

I'd agree that it's pretty readable once you're used to it. Is it more readable than just using an if statement? Will it be more readable to the new person on your team?

But arguing over readability is hard... I admit this is my preference, not a rule.