1

Possible Duplicate:
javascript test for existence of nested object key

if (typeof MyApp != 'undefined' &&
    typeof MyApp.User != 'undefined' &&
    typeof MyApp.User.current != 'undefined' &&
    typeof MyApp.User.current.language != 'undefined') {

   console.log(MyApp.User.current.language);
}

this feels wrong. Can this if statement be written in some nicer way?

Community
  • 1
  • 1
Simon
  • 422
  • 5
  • 19

2 Answers2

1

One simple way is this:

try {
    console.log(MyApp.User.current.language);
} catch(e) {}

or if you don't want "undefined" to be output if MyApp.User.current exists, but MyApp.User.current.language does not, then you would use this:

try {
    if (typeof MyApp.User.current.language != 'undefined') {
        console.log(MyApp.User.current.language);
    }
} catch(e) {}

The try/catch catches the cases for when MyApp or MyApp.user or MyApp.User.current are not defined so you don't have to test for them individually.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

You could perform a decompose conditional refactoring and put that condition in a function:

if (currentLanguageIsDefined()) {
   console.log(MyApp.User.current.language);
}

function currentLanguageIsDefined() {
    return typeof MyApp != 'undefined' &&
           typeof MyApp.User != 'undefined' &&
           typeof MyApp.User.current != 'undefined' &&
           typeof MyApp.User.current.language != 'undefined';
}

... or you can take advantage of the fact that the && operator returns the last value evaluated:

var lang;
if(lang = getCurrentLang()) {
    console.log(lang);
}

function getCurrentLang() {
    return MyApp && MyApp.User && MyApp.User.current && MyApp.User.current.language;
}
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119