1

According to definition nullish assignment , assign only if variable is null or undefined. However the same can also be done using OR operator as shown in the below example. Where should we exactly use nullish assignment operator over logical OR operator?

let a = null;
let b = undefined;
a ||= 10;
console.log(a); // output: 50

b ||= 'string is empty.';
console.log(b); // output: "string is empty."

let a = null;
let b = undefined;

a ??= 10;
console.log(a);  // output: 50

b ??= 'string is empty.';
console.log(b); // output: "string is empty."
brk
  • 48,835
  • 10
  • 56
  • 78

1 Answers1

1

?? is useful when you don't want to check all falsy values:

const bla = 0;
const foo = bla ?? 1; // 0 is a falsy value but ?? only checks null/undefined
console.log(foo)

vs

const bla = 0;
const foo = bla || 1; // `bla` can be any falsy value and `foo` will be 1
console.log(foo)
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32