DEV Community

hemanth.hm
hemanth.hm

Posted on • Edited on

Logical assignment operators in JavaScript

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

Top comments (11)

Collapse
 
cnt000 profile image
Edoardo Gargano

Nice work, thank you for sharing.

I understand better the ??= example with a console.log and changing assignment here: repl

So opts.dog ??= 'bow'; means: if opts.dog is not set, assign bow

Collapse
 
fkereki profile image
Federico Kereki

Hi! I'm not sure -- isn't x ||= y the same as x = x || y ? This is aligned to how other operators (+=, *=, etc.) do work.

Collapse
 
hemanth profile image
hemanth.hm • Edited

x ||= 1 would mean x || (x = 1)

Collapse
 
cascandaliato profile image
cascandaliato

Aren't the two expressions x = x || y and x || (x = y) equivalent?

Collapse
 
mjswensen profile image
Matt Swensen

Nice work, @hemanth ! These will be super handy

Collapse
 
jeromecovington profile image
Jerome Covington

Nice work on a very useful addition to the language. Great to see you stuck with it.

Collapse
 
hakonkrogh profile image
Håkon Krogh

Very useful new features! Looks like you got the variables mixed up in the examples:

x || (y = z);

Should be

x || (x = y);

... unless I got this all wrong?

Collapse
 
hemanth profile image
hemanth.hm

True, fixed it. I was trying to bring in another variable.

Collapse
 
andreasloukakis profile image
Andreas Loukakis

Imho, it would be important to emphasise on ??= checking for null and undefined, while ||= checking for falsy values. Could save some bugs :D

Same as:
0 || 42 // 42
0 && 42 // 0
0 ?? 42 // 0

Collapse
 
hemanth profile image
hemanth.hm

Some comments may only be visible to logged-in visitors. Sign in to view all comments.