Explain Codes LogoExplain Codes Logo

What does the construct x = x || y mean?

javascript
short-circuit-evaluation
default-function-parameters
falsy-values
Alex KataevbyAlex Kataev·Aug 25, 2024
TLDR

The construct x = x || y uses the logical OR || to set x to y if x is a falsy value. It quickly provides default values, a convenient way for dealing with optional or missing inputs in JavaScript.

let x = null; let y = "default"; x = x || y; // When x got nothing to show, y steals the show! console.log(x); // "default"

Logical OR breakdown

The || operator returns the first truthy value it encounters if any, or the last value if none are truthy. This is known as short-circuit evaluation. Evaluation stops at the first truthy value.

Leveraging for default function parameters

In the pre-ES6 era, a common method for assigning default values to function parameters was x = x || y. This pattern prevents falsy values from being passed to functions:

function greet(message, name) { name = name || 'Guest'; // If no name, everyone becomes 'Guest'! console.log(message + ', ' + name + '!'); } greet('Welcome'); // "Welcome, Guest!"

However, ECMAScript 6 introduced default function parameters, allowing for a cleaner, more explicit syntax. The ES6 syntax is now preferred due to improved readability and broader browser compatibility:

function greet(message, name = 'Guest') { console.log(message + ', ' + name + '!'); } greet('Welcome'); // "Welcome, Guest!"

Taking it further: Falsy values in JavaScript

JavaScript has several falsy values, such as null, undefined, 0, false, '', and NaN. Even though x = x || y comes in handy, it might override valid, but falsy values like 0 with y. Oops, it thought 0 was nothing!

let x = 0; let y = 5; x = x || y; // 0 tried to play hide-n-seek and got replaced! console.log(x); // 5

To handle such cases, it's often better to explicitly check if x is null or undefined:

x = (x !== undefined && x !== null) ? x : y;

Interpreting the logical OR outcome

The logical OR operator doesn't always convert the result to a boolean. Instead, it returns the original value that was found to be a truthy, which could be any data type.