So, what is nullish coalescence in JavaScript you ask? You’ve seen the double question mark “??” symbol in JavaScript and wondered what this is what action it performs. This is called Nullish Coalescence and it’s a very simple yet elegant feature in JavaScript or TypeScript. Let’s have a look. 

In a nutshell, nullish coalescene checks the value of a variable and according to that value, it would either leave at that or assign it a default value. Kind of like an if-else conditioning. Simple right!  

Let’s look at an example. 

				
					const details = {
    name: "John",
    age: 25
}

console.log(details.age);       // THIS WOULD PRINT 25
console.log(details.weight);   // THIS WOULD PRINT 'undefined'
				
			

Since the object details does not hold the key “weight”, it would return ‘undefined’ when called in line 7. And therefore, if we want some default value to get printed instead of ‘undefined’, we could use nullish Coalescence here. This even works for null as return type Like so: 

				
					console.log( details.weight ?? ‘70 kg’ );   // THIS WOULD PRINT ‘70 kg’ even if the return is ‘undefined’
				
			

So, basically “??” operand checks if the left side is either null or undefined, and if it is then it would go and assign the value set on the right side of the symbol “??”. That’s it! 

TL;DR  

If your defined variable could have a ‘null’ value or ‘undefined’ response stored in it and you would rather have a default value stored in it instead, then nullish Coalescence is the way to go. 

				
					var temp = ‘John’ ?? ‘some name’ 	// temp = John
var temp = undefined ?? ‘some name’ 	// temp = some name
var temp = null ?? ‘some name’ 		// temp = some name