Nullish coalescing operator (??) in Javascript
Nullish coalescing operator (??), introduced in ECMAScript 2020 (ES11), simplifies the process of handling default values for variables that might be Either null or undefined.
Basics of Nullish coalescing operator (??)
This is a logical operator that returns its right-hand side operand when its left-hand side operand is Either null
or undefined
, and otherwise returns its left-hand operand. This treats undefined
and null
as specific values.
Syntax:
Difference between || and ?? :
Both are used to provide the default/fallback values to variables, but there is a major difference between them and that difference is the use-case of ?? operator.
Falsy values:
As we know, the falsy values in JavaScript are:
false
null
undefined
- Not a Number keyword
NaN
- Empty string
""
- Number zero
0
Example:
const value=leftOperand || rightOperand;
The || operator always returns the rightOperand if the leftOperand will be ANY of falsy values (false, 0, ""
, NaN, null, undefined).
const value=leftOperand ?? rightOperand;
The ?? operator always returns the rightOperand if the leftOperand will be EITHER null or undefined falsy values (null, undefined).
Note: This is the major difference between || and ?? .The ?? operator only returns its right operand if the left operand value will be Either null or undefined. You can consider the Nullish Coalescing Operator ??
a special case from the Logical OR Operator ||
.
Use-Cases and Examples
1-Assigning a default value to a variable
As I explained earlier, both (|| and ??) operators are used to provide the fallback/default values to variables, but ?? is commonly used to provide default values for variables that may be null
or undefined
.
Example:
let value = null;
let result = value ?? "Default Value";
console.log(result); //Default Value
let num=10;
let count = 0;
let emptyStr = "";
let nan=NaN;
let booleanValue=false;
let userName=null;
let uninitiallizedVar;
console.log(num || 100); //10
console.log(num ?? 100); //10
console.log(count || 10); //10
console.log(count ?? 10); //0
console.log(emptyStr || 'Default string');// 'Default String'
console.log(emptyStr ?? 'Default string');// ''
console.log(nan || 'It is NaN'); //It is NaN
console.log(nan ?? 'It is NaN'); // nan
console.log(booleanValue || 'It is a false value'); // 'It is a false value'
console.log(booleanValue ?? 'It is a false value'); // false
console.log(userName || 'Devin'); // Devin
console.log(userName ?? 'Devin'); // Devin
//Note both log Devin
console.log(uninitiallizedVar || 10); //10
console.log(uninitiallizedVar || 10); //10
//Note both log 10
Avoiding Falsy Values: When using ||
operator for providing default values, falsy values like 0
, ''
, false
, etc., are not treated differently from null
or undefined
. The nullish coalescing operator specifically checks for null
or undefined
.
let value = 0;
let result = value || "Default Value";
console.log(result); // Default Value
let result2 = value ?? "Default Value";
console.log(result2); // 0
2-Function parameters
It can be used to provide default values for function parameters.
function greet(name) {
name = name ?? "Guest";
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!
3-Combination with Optional chaining (?.) operator
Optional chaining can be combined with nullish coalescing (??
) to provide default/fallback values for null
or undefined
.
Optional chaining operator (?.) which is useful to access a property of an object that may be null
or undefined
. Combining them, you can safely access a property of an object that may be nullish (null or undefined) and provide a default value if it is.
Example 1:
const user = {
name: 'David',
address: null,
};
Traditional Approach:
const city = user.address ? user.address.city : 'Sydney';//Sydney
With Optional Chaining:
const city= user.address?.city ?? 'Sydney'; //Sydney
Example2:
const user= { name: "Devin" };
console.log(user.name?.toUpperCase() ?? "not available"); // "DEVIN"
console.log(user.city?.toUpperCase() ?? "not available"); // "not available"
Checking Object Properties: When accessing properties of an object that might be null
or undefined
, the nullish coalescing operator can be useful for providing a default value.
let obj = { prop: null };
let propValue = obj.prop ?? "Default Value";
console.log(propValue); //Default Value
4-Combination with || and && operators
It is not possible to combine both the AND (&&
) and OR operators (||
) directly with ??
. A syntax error will be thrown in such cases.
Examples:
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
let firstName;
let lastName = null;
let username = firstName || lastName ?? "Guest";
// Error: Unexpected token '??'
console.log(username);
This is because JavaScript won’t be able to determine which operator it needs to evaluate first. Instead, provide parenthesis to explicitly indicate the precedence:
(null || undefined) ?? "foo"; // returns "foo"
let firstName;
let lastName = null;
let username = (firstName || lastName) ?? "Guest";
console.log(username); //Guest
Conclusion:
The Nullish Coalescing Operator (??
) empowers JavaScript developers with a powerful tool for handling default values or safe checks concisely and robustly.