Optional Chaining Operator (?) and Nullish Coalescing Operator (??)
Optional Chaining Operator(?) (**)
//Car object
const car = {
attributes: {
year: 2021,
model: "Ferrari"
}
}
Before in javascript to validate that the attributes of an object exist, it was necessary to use the And operator (&&)
to validate if the attributes of the object existed.
See the following example:
if (car && car.attributes && car.attributes.model) {
console.log('Exist', car.attributes.model)
} else {
console.log('Do not exist')
}
# => "Exist Ferrari"
Now with Optional Chaining Operator (?)
We can validate if the property exit will return undefined if the property attributes or model doesn’t exist.
if (car?.attributes?.model) {
console.log('Exist', car.attributes.model)
} else {
console.log('Do not exist')
}
# => "Exist Ferrari"
Nullish Coalescing Operator(??) (**)
//Car object
const car = {
attributes: {
year: 2021,
model: "Ferrari"
}
}
If we want to get the car model then we would like below:
console.log(car.attributes.model);
# => "Ferrari"
Now the new car object does not have the model property, so we get an undefined value
//Car object
const car = {
attributes: {
year: 2021,
}
}
console.log(car.attributes.model);
# => "undefined"
To avoid the undefined value the OR (| |)
operator can be used, It will now return the value BMW because the property model is undefined. But what if the name property is empty like below example
console.log(car.attributes.model | | "BMW" );
# => "BMW"
Now the problem is when the property model exists but has an empty, undefined or null value we will get the BMW value and this is not right.
//Car object
const car = {
attributes: {
year: 2021,
model: ""
}
}
console.log(car.attributes.model | | "BMW" );
# => "BMW"
The solution for this problem is to use the Nullish Coalescing Operator (??), Which will print the result as an empty string.
console.log(car.attributes.model ?? "BMW" );
# => ""