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.
Top comments (5)
Totally agree. Let’s let this kind of things to minifiers.
You can use Optional chaining:
myFunction?.();
developer.mozilla.org/en-US/docs/W...
I didn't know they had optional chaining in JS! Thank you!
I think it's pretty readable and understandable. Also people don't know so many things, shouldn't we use those things?
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.