Using && and || outside of if-clause in JavaScript

NAVIGATION

If-clause operates on truthy and falsy values

Use && to safe-guard against undefined

Use || to provide default value

Readability

You may have used the && and || operators when writing a condition in an if-clause. But did you know that, in JavaScript, they evaluate to the expression values, such as strings and numbers, instead of the boolean values true and false?

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

The fact that && and || operators evaluate to strings and numbers does not break the if-clause because conditions are evaluated differently in JavaScript.

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.

const sessionId = request.session && request.session.id;

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.

const name = user.name || 'Guest';

The definition for || is

The ||-operator evaluates to left hand side expression if it is truthy, otherwise to right hand side expression.

Readability

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.

Semantic Versioning Cheatsheet

Semantic Versioning Cheatsheet

Learn the difference between caret (^) and tilde (~) in package.json.

Get Cheatsheet

Loading Comments