Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't check nested object variables in a single line

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading