Hemanth's Scribes

javascript

Logical Assignment Operators in JavaScript

Author Photo

Hemanth HM

Thumbnail

Logical assignment operators in JavaScript combine Logical Operators and Assignment Expressions.

The Operators

// "Or Or Equals"
x ||= y;
x || (x = y);

```javascript
// "And And Equals"
x &&= y;
x && (x = y);

```javascript
// "QQ Equals" (Nullish Coalescing)
x ??= y;
x ?? (x = y);

Example: updateID Function

Say you have a function updateID, it can vary in the following ways:

const updateID = user => {
  // We can do this
  if (!user.id) user.id = 1

  // Or this
  user.id = user.id || 1

  // Or use logical assignment operator
  user.id ||= 1
}

Using with Nullish Coalescing

You could also use it with ??:

function setOpts(opts) {
  opts.cat ??= 'meow'
  opts.dog ??= 'bow';
}

setOpts({ cat: 'meow' })

This is on stage-4 and you should be able to use it today!

I am happy that I was able to co-champion this proposal. 7 Years ago it was just a thought!

#javascript#es2021#tc39
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.