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>

   let firstName = null;
   let username = firstName ?? "Rokcy";

   let name = undefined ?? "Rokcy";




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';
// output: "default string"

const baz = 0 ?? 42;
// 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 *