What does the construct x = x || y mean?
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.
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:
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:
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!
To handle such cases, it's often better to explicitly check if x is null or undefined:
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.
Was this article helpful?