Nullish coalescing operator

13 0 0
                                        

Nullish coalescing operator (??)

Syntax:

let variableName = value1 ?? value2

It checks if value1 is null or undefined, if then variableName is equal to value2. If value1 is not null or not undefined, then variableName is equal to value1.

==============

let x = prompt("Enter any number", 0);

function displayingX(){

     if(x == 0){

          x = alert("x was zero!");

     }

     return x ?? 999;

}

==============

HTML

document.write(displayingX())

Result:

999

Note: If you haven't change the value of x and just press ok, the x=0. Then, it will display an alert that says, x was zero. Also, it will assign x a value of undefined since we equate it to alert. Since value1 is undefined, it will display 999. Canceling the prompt would result to 999 too. Put any number that is not zero, to display x.


Note:

1. I did not include the Comparison operator like greater than and so on because it was the same in java.

2. I did not include the Logical operator like AND and so on because of the same reason.

Javascript ProgrammingWhere stories live. Discover now