What is double question mark in Javascript?

Introduction

In this article, I will discuss what is double question mark in Javascript? in-depth. So what is double question mark in javascript? The double question mark in javascript is known as a Nullish Coalescing Operator. Nullish Coalescing Operator is introduced in ECMAScript 2020 (ES11) which is represented by “??”. This operator is introduced to provide a better way to assign default values.

Basics

In javascript nullish coalescing operator is utilized to deliver a default value when facing null or undefined values. The nullish coalescing operator considers empty string & zero as valid values and considers null and undefined as the default value.

Working Strategy

In this operator, the expression is evaluated on the left-hand side & if the value is undefined or null nullish coalescing operator returns the value on its right-hand side. It can also handle falsy values e.g. if it has a falsy value on its left-hand side (value other than the null & undefined) it will return the falsy value because it considers falsy values as valid values. It also has a requirement that if the left-hand side has a default value (null & undefined) then the right-hand side expression will be evaluated.

Code Examples

function beautiful(name) {
  const displayName = name ?? 'User';
  console.log(`Hello, ${displayName}!`);
}

beautiful(); // Output: 'Hello, User!'
beautiful('Ali'); // Output: 'Hello, Ali!'
Code Explanation

In the first step, a beautiful function takes “name” as a parameter. In the second step, the constant variable is declared equal to the name then the nullish coalescing operator is used & on the right-hand side the “User” is placed. Nullish coalescing operator displays default value if no value for the “user” is provided. You can see the functionality works if the name parameter is null or undefined.

You can also learn more about what is double question mark in javascript? on Mdn web docs.

Similar Posts