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

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading