-1

Example:

const genre = {
  "action": {
    "rating": "8",
    "movie": "John Wick"
  },
  "romance": {
    "rating": "6.5",
    "movie": "The Girl Next door"
  }
}

For accessing the movies based on the 'Genre' we can use genre.action

But why genre?.action also works. Can anyone explain I've seen people use this '?.' to access the JSON objects.

Thanks:)

Anonymous
  • 13
  • 5
  • 2
    Voting to close - duplicate of [Null-safe property access (and conditional assignment) in ES6/2015](https://stackoverflow.com/questions/32139078/null-safe-property-access-and-conditional-assignment-in-es6-2015) – esqew Aug 02 '21 at 15:01

1 Answers1

2

This is call Optional chaining which allows to access the key of the nested object only if the key is not nullish or undefined

const genre = {
  "action": {
    "rating": "8",
    "movie": "John Wick"
  },
  "romance": {
    "rating": "6.5",
    "movie": "The Girl Next door"
  }
}

console.log(genre.action?.rating);
console.log(genre.someKey?.someKey)
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
brk
  • 48,835
  • 10
  • 56
  • 78