DEV Community


Logical assignment operators in JavaScript
Just an other curious 🐜
Updated on ・1 min read

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

//"Or Or Equals"
x ||= y;
x || (x = y);
// "And And Equals"
x &&= y;
x && (x = y);
// "QQ Equals"
x ??= y;
x ?? (x = y);

So, say you have a function updateID it can vary in the below ways:

const updateID = user => {

  // We can do this
  if (! = 1

  // Or this = || 1

  // Or use logical assignment operator. ||= 1

You could also use it with ??

function setOpts(opts) { ??= 'meow' ??= '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!


Discussion (11)

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 ??= 'bow'; means: if is not set, assign bow

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.

hemanth profile image Author • Edited

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

cascandaliato profile image

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

mjswensen profile image
Matt Swensen

Nice work, @hemanth ! These will be super handy

jeromecovington profile image
Jerome Covington

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

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?

hemanth profile image Author

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

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

hemanth profile image Author
mariankeeling profile image

I have recently got the similar assignment in javascript and was not sure about its solution. That is why I decided to turn to website and hire the professional expert who is able to do my assignment within the shortest deadline and with the best price.