Javascript Logical Nullish Assignment equivalence

Viewed 624

I was visiting MDN article for Logical Nullish Assignment. The equivalence version provided by MDN was x ?? (x = y) which isn't clear enough and needs digging deeper.

Is this code:

let x = null;

x ??= 12;

equivalent to:

let x = null;

if (x === null || x === undefined) {
  x = 12;
}
2 Answers

Yes, it only assigns if x is nullish.

x ?? (x = y)

or

if (x === null || x === undefined) {
  x = 12;
}

It is NOT equivalent to

x = x ?? y

There is a difference and you can verify this by using const instead of let. That way, reassignment will result in an error. This also applies to other logical assignment like AND (&&=) and OR (||=) assignment operators.

// no const reassignment error here  
// because a || (a = 'updated') doesn't evaluate the second expression
// if it was a = a || 'updated', it would throw an error
const a = 'initial'
a ||= 'updated' 
console.log(a)

const b = null
b &&= 'updated'
console.log(b)

const c = 'initial'
c ??= 'updated' // c ?? (c 
console.log(c)

// The below 3 examples will evaluate the second expression 
// and const reassignment error is thrown
try {
  const d = null
  d ||= 'updated'
} catch (e) {
  console.log("|| Error: " + e.message)
}

try {
  const e = 'initial'
  e &&= 'updated'
} catch (e) {
  console.log("&& Error: " + e.message)
}

try {
  const f = null
  f ??= 'updated'
} catch (e) {
  console.log("?? Error: " + e.message)
}

Related