Can't check nested object variables in a single line

Issue

I need to show a welcome-modal to user on his first time to that page.

This code works fine:

if(this.app_data) {
  if(this.app_data['company']){
    if(this.app_data['company']['welcomed'] === false){
      this.openWelcomeModal();
    }
  }
}

The problem is the messy code checking nested variable structure.

The clear way to do it would be use a single line like this:

if(this.app_data['company']['welcomed'] === false){
  this.openWelcomeModal();
}

But this generates error:

    core.js:7376 ERROR TypeError: Cannot read properties of undefined (reading 'welcomed')
        at SafeSubscriber._next (game.page.ts:46:39)

Is there any way to do it in a single line, without need to check each level of nested object?

Solution

Optional chaining to the rescue!

if(this.app_data?.['company']?.['welcomed'] === false){
  this.openWelcomeModal();
}

Answered By – nate-kumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published