1. Nullish Coalescing:
The nullish coalescing operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and if left hand side operand is not null or undefined then returns left hand side operands. The nullish coalescing operator sign is '??' .
const student = {
name:'abhishek',
education:'b.tech'
};
const data = student.name ?? 'default value';
console.log(data) //abhishek
OR
const student = {
education:'b.tech'
};
const data = student.name ?? 'default value';
console.log(data) //default value
Assign Default Value to a Variable
Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||
).
const data;
const data1 = data || 'Hello';
console.log('data1') //Hello (because data is not assign any value so here data is undefined Therefore print 'Hello' by default.
In this OR(||) operator falsy value(0, NAN, " ", false) does't return. In this case always retuns default value.
But in this nullish coalescing operator return falsy value (0, NAN, " ", false) .
const student = {
name : 'abhishek',
course : '',
};
const data = student.course || 'Hello';
console.log(data) //Hello (because || operator avoids (''), Therefor print default value 'Hello'.
BUT;
const student = {
name : 'abhishek',
course : '',
};
const data = student.course ?? 'Hello';
console.log(data) //'' (because nullish coalescing does't avoid (''), Therefore print '' ;
2. Optional Chaining:
The optional chaining (?.) is a safe way to access nested object properties, even if an intermediate property doesn’t exist.
The optional chaining (?.) stops the evaluation if the value before (?.) is undefined or null and returns undefined .
- we can stop the error by using optional chaining, Means if any property does't exist in any object then we can print undefined by using optional chaining .
const student = {
name : 'abhishek',
course : 'b.tech',
city : 'gonda'
};
const data = student?.name;
console.log(data) //abhishek;
OR
const student = {
course : 'b.tech',
city : 'gonda'
};
const data = student?.name;
console.log(data) //undefined; (instead of error)
With optional chaining, you can use the "?" operator to chain multiple property or method accesses together, and if any of the intermediate values in the chain is null or undefined, the expression will short-circuit and return undefined instead of throwing an error.
const user = {
name: 'abhishek',
address: {
city: 'gonda',
country: 'india'
}
};
const country = user?.address?.country;
console.log(country); //india
const state = user?.address?.state;
console.log(state); // undefined