Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 that 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 leaving it uninitialized; in the end color 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 will print ‘hello’.
A more verbose way to achieve something similar (using falsy check instead of nullish) would be:
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 |