0
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
      }
    }
  }
alramdein
  • 810
  • 2
  • 12
  • 26
  • 1
    dv not me, but have you seen the [optional chaining operator `?.`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? – Nina Scholz Sep 23 '21 at 07:06
  • Votes first and foremost express how useful a question is to the rest of the world. I've seen this very question at least 10~20 times in the past, so I can see why people don't consider it very useful. – Ivar Sep 23 '21 at 07:15
  • @Ivar I see. But the problem is I don't know how to search for this properly. The one that I find is [this](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) which is so uneffective in my opinion. But now I know it is `optional chaining operator`. Thank you for the feedback – alramdein Sep 23 '21 at 07:19
  • @alramdein I'm not blaming you for not finding it. Finding it sometimes requires you to know the answer upfront so you know the keywords to look for. The question you are referring to however does mention optional chaining at the end of the accepted answer. – Ivar Sep 23 '21 at 07:24

2 Answers2

1

Try This, "?."

const object = {
    level1: {
      level2: {
        level3: 'foo'
      }
    }
}

console.log('object: ',object?.level1?.level2?.level3)
1

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);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • @NinaScholz has already answer my question and give me a proper reference. But since I need to accept an answer, I'll accept this rather than the first one because this is provide me more information I need about it. – alramdein Sep 23 '21 at 07:15
  • @alramdein _"I need to accept an answer"_ - If the question is closed (e.g. because there's a fitting duplicate) you don't have to accept an answer. – Andreas Sep 23 '21 at 07:18