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 |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!