Content:
JavaScript provides a couple of operators to simplify null
handling. Specifically, these operators handle nullish values – either null
, or undefined
.
These operators can simplify your code, particularly when handling errors (producing nullish return values), or default value assignment.
Two operators you should look to use in your code are explained below.
Nullish Coalescing Operator
The nullish coalescing operator (??
) is a conditional operator, which returns a second value should the first value be either null
or undefined
.
console.log('JS is cool' ?? 'hello world'); // 'JS is cool'
console.log(null ?? 'hello world'); // 'hello world'
In a way, it works similarly to ||
(OR), but only returning the right-hand value if the left-hand value is nullish
(rather than falsy
, like ||
)
It can be used to set a default value, where one has not already been set. The right-hand side is not evaluated if the left-side is not nullish.
Nullish Coalescing Assignment
Nullish coalescing assignment assigns a value if the current value is either null
, or undefined
. If the value on the left-hand side is any other value, no assignment takes place. Because of this, it can be used with a variable defined as a const
.
const x = 1;
x ??= 5; // No error is thrown
console.log(x) // 1
It’s an incredibly useful way to set a default value for a variable. It can also be used to set default values for object properties.
class Car {
function setValues(values) {
values.colour ??= 'red';
values.topSpeed ??= 150;
}
}
car = new Car();
car.setValues({colour: 'green'})
console.dir(car) // {colour: 'green', speed: 150}