Open In App
Related Articles

JavaScript Nullish Coalescing(??) Operator

Like Article
Save Article
Report issue

Nullish Coalescing Operator is a new feature introduced in this ECMA proposal that has now been adopted into the official JavaScript Specification. This operator returns the right-hand value if the left-hand value is null or undefined. If not null or undefined then it will return left-hand value.

There are values in JavaScript like 0 and an empty string that are logically false by nature. These values may change the expected behavior of the programs written in JavaScript. All the reoccurring problems led to the development of the Nullish Coalescing Operator. The Nullish Coalescing Operator is defined by two adjacent question marks ?? :

When the passed parameter is less than the number of parameters defined in the function prototype, it is assigned the value of undefined. To set default values for the parameters not passed during the function call, or to set default values for fields not present in a JSON object, the above method is popular.




variable ?? default_value

Below are examples of the Nullish Coalescing Operator.

Example 1: In this example, we will see a basic function using the nullish coalescing operator


function foo(bar) { 
    bar = bar ?? 55; 
foo(); // 55 
foo(22); // 22




Example 2: The more common use case is to set default values for JSON objects as follows. 


const foo = { 
    bar: 0 
const valueBar = ?? 42; 
const valueBaz = foo.baz ?? 42; 
// Value of bar: 0 
console.log("Value of bar: ", valueBar); 
// Value of bar: 42 
console.log("Value of baz: ", valueBaz);



Value of bar:  0
Value of baz:  42

Supported Browsers: The browsers supported by JavaScript Nullish Coalescing Operator are listed below:

  • Google Chrome 80
  • Firefox 72
  • Edge 80
  • Opera 67
  • Safari 13.1

Last Updated : 28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads