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

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 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.

1 var sessionId = request.session &&;

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.

1 var name = || 'Guest';

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.

Asynchronous calls are hard

Asynchronous calls are hard

Learn how to turn the vision in your head into working program. Get Mini Email Course on asynchronicity and two chapters from Finish Your Node App book.

Get Two Book Chapters