Nullish coalescing is a new JavaScript feature, introduced in ES2020, that helps to handle null
or undefined
values more efficiently. It is represented by two question marks (??
) and is used to provide a default value for a variable if its value is null
or undefined
.
leftExpr ?? defaultValue
Here, leftExpr
is the name of the variable whose value we want to check, and defaultValue
is the value that we want to assign to the variable if its value is null
or undefined
.
Remember nullish coalescing operator only returns the second operand when leftExpr
evaluates to either null
or undefined
, but not other falsy values like logical OR (||
) operator.
// There are six falsy values in JavaScript:
// false, null, undefined, zero (0), not a number (NaN), empty string('')
let foo = 0;
console.log(foo || 100); // 100
console.log(foo ?? 100); // 0
Nullish coalescing is useful in scenarios where we want to assign default values to variables, especially when dealing with objects or arrays. Let’s consider some practical examples where nullish coalescing can be used:
function printMessage(message) {
message = message ?? 'Hello, World!';
console.log(message);
}
printMessage(); // Output: Hello, World!
printMessage('Hi there!'); // Output: Hi there!
const user = {
name: 'John',
age: null,
email: undefined,
};
const userName = user.name ?? 'Unknown';
const userAge = user.age ?? 18;
const userEmail = user.email ?? 'user@example.com';
console.log(userName); // Output: John
console.log(userAge); // Output: 18
console.log(userEmail); // Output: user@example.com
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
const name = data.name ?? 'Unknown';
const username = data.username ?? 'Unknown';
const email = data.email ?? 'Unknown';
console.log(`Name: ${name}, Username: ${username}, Email: ${email}`);
})
.catch(error => console.error(error));