Assigning values to variables in JS is the core of what we do. In addition, conditionally doing so is important to the bulk of the logic we write. The normal train of thought would be to do so through an if...else operator, switch...case statement block, or something similar. However, there are some new ways to accomplish this. Logical assignments!

A logical assignment is a cool way to accomplish the same goal, but in a much more simpler way, with fewer lines of code. Let’s take a look!

let a = 1;
let b = 2;

a &&= b;
a; // 2
// The above logic equates to
if (a) {
  a = b;
}

a = null;
a ||= b;
a; // 2
// The above statement equates to the opposite of the first one
if (!a) {
  a = b;
}

a = undefined;
a ??= b;
// The above logic equates to
if (a === null || a === undefined) {
  a = b;
}