- Home
- TypeScript
- What is Nullish Coalescence in ...
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
Recent Comments
Categories
- Angular
- AWS
- Backend Development
- Big Data
- Cloud
- Database
- Deployment
- DevOps
- Docker
- Frontend Development
- GitHub
- Google Cloud Platform
- Installations
- Java
- JavaScript
- Linux
- MySQL
- Networking
- NodeJS
- Python
- Python Flask
- Report
- Security
- Server
- SpringBoot
- Subdomain
- TypeScript
- Uncategorized
- VSCode
- Webhosting
- WordPress
Search
Recent Post
Understanding Linux Scheduling Algorithm: A Comprehensive Guide
- 13 June, 2023
- 3 min read
How to add routing in Angular
- 9 May, 2023
- 4 min read
What is Data at Rest in Cloud
- 13 March, 2023
- 2 min read
Featured Videos
All Tags
Amazon Web Services
Angular
API
AWS
Bash
Bash Scripting
Big Data
Cloud Server
Cluster
Command Line
CRUD
Database
Deployment
DevOps
Docker
Elementor
GitHub
Google Cloud
Google Cloud Platform
HBase Database
Header
installation
JasperReport
Java
JavaScript
Linux
Local Server
MySQL
NodeJS
npm
Programming
Publish
Puppeteer
Python
S3 Bucket
Security
SpringBoot
SSH
Terminal
ternary operators
TypeScript
Virtual Machines
Webhosting
Windows
WordPress