Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Nullish Coalescing Operatorin JavaScript

The nullish coalescing operator (??) is a logical operator that takes two arguments. It returns the right-hand side operand when its left-hand side operand is null or undefined. otherwise, it returns its left-hand side operand.

Syntax

                            
leftExpr ?? rightExpr
                     
                            
                        

If leftExpr is not null or undefined, then returns leftExpr

if leftExpr is either null or undefined, then returns rightExpr

Example

In the following code, since email is undefined, the ?? returns the "No Email Selected".

                            
let email
 
let selecteditem =  email ?? "No Email Selected";
 
console.log(selecteditem)   //No Email Selected
                     
                            
                        

If the email already has a value, it returns the email.

                            
let email=""
let selecteditem =  email ?? "No Email Selected";
console.log(selecteditem)   //""
 
 
email="0"
selecteditem =  email ?? "No Email Selected";
console.log(selecteditem)   // 0
 
                     
                            
                        

Difference with ||

You can also make use of the logical OR operator. Because null & undefined are falsy values.

                            
let email
let selecteditem =  email || "No Email Selected";
console.log(selecteditem)   //No Email Selected 
 
 
email="mail@example.com"
selecteditem =  email || "No Email Selected";
console.log(selecteditem)   //"mail@example.com" 
 
                     
                            
                        

But, if email, has other falsy values like false, 0,-0 , 0n, "", NaN, then the || & ?? produces different outputs.

                            
let email=""
let selecteditem =  email || "No Email Selected";
console.log(selecteditem)   //No Email Selected
 
 
selecteditem =  email ?? "No Email Selected";
console.log(selecteditem)   //
 
 
                     
                            
                        

Difference with Conditional Operator

We can mimic the ?? using the Ternary Conditional Operator.

                            
let email
let selecteditem =  (email != undefined || email != null ) ? email:  "No Email Selected"
console.log(selecteditem)   //No Email Selected
 
                     
                            
                        

Assiging Default Values

One of the use cases of the ?? operator is assigning the default value.

We usually use the || to assign a default value. In the following example, we have not given any value to score. Hence it is undefined. Both the || & ?? does not return the score, but prints the message “Please enter your score”

                            
let score;
 
console.log(score|| "Please enter your score")
 //Please enter your score
console.log(score?? "Please enter your score")
 //Please enter your score
 
                     
                            
                        

Now, assume that the user entered his score as 0, which is a valid score. But the || operator still returns the message “Please enter your score”, because 0 is false. But the ?? returns the score correctly.

                            
score=0
console.log(score || "Please enter your score")
 //Please enter your score
console.log(score ?? "Please enter your score")
 //0
 
                     
                            
                        

Short-circuiting

?? like || & && operators, stops evaluating if the left-hand operand is not null/undefined. Hence the right-hand expression is not evaluated.

For Example, the following code evaluates the getNumber and values of a becomes 11.

        
let a=10 
 
 function getNumber() {
    a=a+1
    return a;
 }
  
  
 let b = ( null ?? getNumber() ) 
  getNumber() not invoked
  
 console.log(a);  //11

 
        
    

But, here the ?? returns with the string ‘Hello’ and getNumber() is never invoked. The value of a remains at 10.

        
let a=10 
 
function getNumber() {
   a=a+1
   return a;
}
 
 
let b = ( "Hello" ?? getNumber() ) 
 //getNumber() is not invoked
 
console.log(a);  //10