DEV Community

Cover image for Logical assignments and their use cases
Deepankar Bhade
Deepankar Bhade

Posted on • Originally published at dpnkr.in

Logical assignments and their use cases

Binary operations and conditional rendering are something we do quite frequently while building applications. This article is about logical assignment operators that were introduced in ES2021.

it's important to understand truthy & falsy before we get to the good part you can read my blog on the topic if you want to.

Logical OR ||=

You might have encountered a situation were you want to assign a default value incase the input is not provided. One of the ways to do this is:

let input;
if (input === '' || typeof input === 'undefined') {
  input = 'Default value';
}
console.log(input);
Enter fullscreen mode Exit fullscreen mode

This works and does assign the default value but we might also want to include the case of null, false, or basically falsy values. This is exactly where Logical OR comes in handy.

let input;
input ||= 'Default value';
console.log(input);
Enter fullscreen mode Exit fullscreen mode

||= would only assign only if the input is falsy.

Logical AND &&=

Opposite of Logical OR is Logical AND which would assign only if the input is truthy.

let input = 10;
input &&= undefined;
console.log(input);
Enter fullscreen mode Exit fullscreen mode

This would assign input as undefined. This assignment operator can be helpful if we want to reset the value of a variable.

Logical nullish ??=

The 2 operators we talked about are based on truthy & falsy values. But what if we only want to perform assignments based on undefined or null value.

NOTE: undefined and null are falsy under Boolean context and are also referred to as being nullish values.

A really good example from MDN docs explaining this:

let obj = {
  name: 'deepankar',
};
obj.language ??= 'javascript';
console.log(obj);

// OUTPUT:
// {
//     "name": "deepankar",
//     "language": "javascript"
// }
Enter fullscreen mode Exit fullscreen mode

Since there's no language key in the object it will be undefined and hence performing the assignment.

Top comments (0)