Skip to content

Double question mark in JavaScript | Code

  • by

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:

Double question mark in JavaScript

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

Do 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

Leave a Reply

Your email address will not be published. Required fields are marked *