How to handle 'undefined' in JavaScript

Javascript

Javascript Problem Overview


> Possible Duplicate:
> Detecting an undefined object property in JavaScript

From the below JavaScript sample,

try {
    if(jsVar) {
        proceed();
    }
}
catch(e) {
    alert(e);
}

this jsVar is declared and initialized in another file.

The problem is that code throws undefined error when this code is executed before the other file (where its declared and initialized) is executed. That is why it is surrounded by try and catch.

What's the best way to handle this undefined error than try catch?

Javascript Solutions


Solution 1 - Javascript

You can check the fact with

if (typeof jsVar == 'undefined') {
  ...
}

Solution 2 - Javascript

As is often the case with JavaScript, there are multiple ways to do this:

typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window

The first two should be equivalent (as long as foo isn't shadowed by a local variable), whereas the last one will return true if the global varible is defined, but not initialized (or explicitly set to undefined).

Solution 3 - Javascript

In JavaScript, the following values will cause the if condition to fail and not execute its statement: null, undefined, false, NaN, the number 0, and the empty string ''.

Assuming that the variable jsVar is a boolean and that we want to call the proceed() method when jsVar is true, we can do the following check.

if (jsVar && jsVar == true)
    proceed();

The above code snippet first check that jsVar has been defined and then checks that its value is true. The if condition will be satisfied only if both the conditions are met.

If jsVar is not a boolean then we can substitute the appropriate check in place of jsVar == true in the code above.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMadhuView Question on Stackoverflow
Solution 1 - Javascriptalex.zherdevView Answer on Stackoverflow
Solution 2 - JavascriptChristophView Answer on Stackoverflow
Solution 3 - JavascriptScottView Answer on Stackoverflow