const object = {
level1: {
level2: {
level3: 'foo'
}
}
}
Let's say I want to get level3's value
console.log(object.level1.level2.level3);
That's so risky considering level1 and level2 could be null or undefined. Is there any simple way to get level3 value safely? Beside check the object properties one by one like this
if (object.level1) {
if (object.level2) {
if (object.level3) {
// do stuff
}
}
}
Try This, "?."
const object = {
level1: {
level2: {
level3: 'foo'
}
}
}
console.log('object: ',object?.level1?.level2?.level3)
That is exactly why you have Optional chaining (introduced in ES2020) in javascript.
It's an operator (?.) which enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is null/undefined so it actually protects you from getting a null reference error.
console.log(object.level1?.level2?.level3);