This enables you to use the && and || 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
Instead of the if-clause deciding on its next move based on the condition being true or false, it decides based on the condition being truthy or falsy.
The definition is
A value is falsy if it is false, null, undefined, '', 0 or 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 && is
The &&-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 ||-operator.
The definition for || is
The ||-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.
Node.js doesn't wait for your database call to finish?
Learn the right mental model for Node apps. Get free email course and two chapters from Finish Your Node App book.