Logical assignment operators in JavaScript

hemanth.hm - Aug 29 '20 - - Dev Community

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

//"Or Or Equals"
x ||= y;
x || (x = y);
Enter fullscreen mode Exit fullscreen mode
// "And And Equals"
x &&= y;
x && (x = y);
Enter fullscreen mode Exit fullscreen mode
// "QQ Equals"
x ??= y;
x ?? (x = y);
Enter fullscreen mode Exit fullscreen mode

So, say you have a function updateID it can vary in the below 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
}
Enter fullscreen mode Exit fullscreen mode

You could also use it with ??

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

setOpts({ cat: 'meow' })
Enter fullscreen mode Exit fullscreen mode

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!

history

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player