Nullish Coalescing Assignment (??=) Operator in JavaScript
Last Updated :
18 May, 2023
This is a new operator introduced by javascript. This operator is represented by x ??= y and it is called Logical nullish assignment operator. Only if the value of x is nullish then the value of y will be assigned to x that means if the value of x is null or undefined then the value of y will be assigned to x.
Let’s discuss how this logical nullish assignment operator works. Firstly we all know that logical nullish assignment is represented as x ??= y, this is derived by two operators nullish coalescing operator and assignment operator we can also write it as x ?? (x = y). Now javascript checks the x first, if it is nullish then the value of y will be assigned to x.
Syntax :
x ??= y // Means : x ?? (x = y)
Example 1 :
Javascript
let x = 12;
let y = null ;
let z = 13;
x ??= z;
y ??= z;
console.log(x)
console.log(y)
|
Output :
12
13
Example 2 :
Javascript
let x = {
name : "Ram"
}
x.name ??= "Shyam" ;
x.age ??= 18;
console.log(x.name)
console.log(x.age)
|
Output :
"Ram"
18
Example 3:
HTML
< h1 >Hello Geeksforgeeks</ h1 >
< p id = "print_arr" ></ p >
< script >
let arr = [1, 2, "apple", null, undefined, []]
// Replace each nullish values with "gfg"
arr.forEach((item, index)=>{
arr[index] ??= "gfg"
})
document.getElementById("print_arr")
.innerText = arr.toString();
//console.log(arr)
</ script >
|
Output :
Supported browsers
- Chrome 85
- Edge 85
- Firefox 79
- Safari 14
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...