JS: variable && function()
Winston Puckett

Winston Puckett @winstonpuckett

About: Calling out the gold in your pull request.

Location:
Portland Oregon
Joined:
Sep 6, 2020

JS: variable && function()

Publish Date: Oct 7 '20
6 5

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.

Comments 5 total

  • Furkan KAYA
    Furkan KAYAOct 7, 2020

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

    • Winston Puckett
      Winston PuckettOct 7, 2020

      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.

  • KVNLS
    KVNLSOct 7, 2020

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

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

    • Winston Puckett
      Winston PuckettOct 7, 2020

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

  • Roberto Tonino
    Roberto ToninoOct 9, 2020

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

Add comment