Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Nullish Coalescing(??) Operator

JavaScript Nullish Coalescing(??) Operator

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.

 

 

Syntax:

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

javascript




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


Output:

55
22

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

javascript




const foo = { 
    bar: 0 
  
const valueBar = foo.bar ?? 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);


Output:

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

RELATED ARTICLES

Most Popular

Recent Comments