More operators: Logical nullish assignment

Remember the nullish coalescing operator ??.

We can combine it with an assignment and we get the logical nullish assignment operator ??=.

Here’s an example, you have a variable color which is set to ‘yellow’.

Using the logical nullish assignment we can say “if this variable is nullish, set it to ‘red’.

let color = 'yellow'

color ??= 'red'

color

Try setting color to null or not initialize it with a value, color in the end will be red.

One place where this is particularly useful is when you pass an object to a function, and this object may or may not have some properties set:

const say = (something) => {
  something.content ??= 'hello'

  console.log(something.content)
}

say({ content: 'x' })

In this case it prints ‘x’ but try passing an empty object, it prints ‘hello’.

This is a simplified version of saying

const say = (something) => {
  if (!something.content)
    something.content = 'hello'
  }

  console.log(something.content)
}

Lessons in this unit:

0: Introduction
1: More assignment operators
2: Logical operators
3: Nullish coalescing
4: Optional chaining
5: ▶︎ Logical nullish assignment