Using && and || outside of if-clause
You may have used the
|| operators when writing a condition in an
This enables you to use the
|| operators in expressions outside of
if-clause. It provides short ways to express an early stop using
&& and to express a default value using
If-clause operates on truthy and falsy values
The fact that
|| operators evaluate to strings and numbers does not break the
Instead of the
if-clause deciding on its next move based on the condition being
false, it decides based on the condition being truthy or falsy.
The definition is
A value is falsy if it is
NaN. A truthy value is any value not considered falsy.
Let us put this information into use.
Use && to safe-guard against undefined
A common situation is to access nested object properties using dot notation. For example
request.session.id. In this case, if any object along the way is
undefined an "Uncaught TypeError: Cannot read property of undefined" error is thrown.
The error can be avoided using
&& to safe-guard against undefined.
Here the expression evaluates to
undefined safely without throwing an error.
The definition for
&&-operator evaluates to left hand side expression if it is falsy, otherwise to right hand side expression.
Use || to provide default value
Another common use case is to retrieve a value, and if it does not exist then use a default value.
This can be achieved using
The definition for
||-operator evaluates to left hand side expression if it is truthy, otherwise to right hand side expression.
These two new tools are nice additions to your toolbox. But as always, readability comes first. Use them wisely, where they fit best. Remember to make sure everyone on your team knows how to use them, for example by passing this article to them.
There are 350 000 NPM packages. Your task: pick one.
Learn what to look for in a reliable NPM package.