null
The primitive value null is used as an intentional "empty value" for variables of any type.
let name = null;
// name is intentionally set to "empty" because it is not
// available
You can check whether a variable is null by using the strict equality operator ===.
let name = null;
name === null;
// => true
Optional Chaining
If you try to retrieve a nested value in an object but the parent key does not exist, JavaScript will throw an error. To easily avoid this, optional chaining was added to the language specification in 2020. With the optional chaining operator ?. you can ensure that JavaScript only tries to access the nested key if the parent was not null or undefined. Otherwise undefined is returned.
const obj = {
address: {
street: 'Trincomalee Highway',
city: 'Batticaloa',
},
};
obj.address.zipCode;
// => undefined
obj.residence.street;
// => TypeError: Cannot read property 'street' of undefined
obj.residence?.street;
// => undefined
References:
Nullish Coalescing
There are situations where you want to apply a default value in case a variable is null or undefined (but only then). To address this, the nullish coalescing operator ?? was introduced in 2020. It returns the right-hand side operand only when the left-hand side operand is null or undefined. Otherwise, the left-hand side operand is returned.
let amount = null;
amount = amount ?? 1;
// => 1
amount = 0;
amount = amount ?? 1;
// => 0
References:
References:
- https://exercism.org/tracks/javascript/concepts/null-undefined
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null
Backlinks