The Double question mark is called the nullish coalescing operator in JavaScript. It allows you to provide a default value to use when a variable expression evaluates to null
or undefined
.
leftExpr ?? rightExpr
If firstValue
is null or undefined
console.log(firstValue ?? secondValue) // secondValue
If firstValue
isn’t null or undefined
console.log(firstValue ?? secondValue) // firstValue
A double question mark in JavaScript
Simple example code using a double question mark (??
). It returns the expression on the right side of the mark when the expression on the left side is null or undefined.
<!DOCTYPE html>
<html>
<body>
<script>
let firstName = null;
let username = firstName ?? "Rokcy";
console.log(username);
//or
let name = undefined ?? "Rokcy";
console.log(name);
</script>
</body>
</html>
Output:
JavaScript evaluates an empty string to false
as in the code below:
let firstName = ""; // empty string evaluates to false in JavaScript
let username = firstName ?? "Guest";
console.log(username); // ""
More examples
const foo = null ?? 'default string';
console.log(foo);
// output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// output: 0
Here’s an example to illustrate its usage:
let variable1 = null;
let variable2 = undefined;
let variable3 = 0;
let variable4 = '';
let variable5 = 'Hello';
console.log(variable1 ?? 'Default Value'); // Output: Default Value
console.log(variable2 ?? 'Default Value'); // Output: Default Value
console.log(variable3 ?? 'Default Value'); // Output: 0
console.log(variable4 ?? 'Default Value'); // Output: ''
console.log(variable5 ?? 'Default Value'); // Output: Hello
The nullish coalescing operator provides a concise way to handle default values in cases where you specifically want to check for null
or undefined
values, rather than any falsy value.
Comment if you have any doubts or suggestions on this JS basic code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version