Search code examples
javascriptmethodsmethodology

Is try / catch (one of) the best ways to keep errors from occuring if a variable is undefined?


I was warned that this post could be too subjective, but I've only been programming for a few weeks, so I'd like to know.

So far I've been using try/catch statements in my JS to keep from throwing errors in case a variable isn't defined when a function is run, but is that the only efficient way to do so?


Solution

  • To test if a regular variable exists, I'd say your best bet is to compare the type to undefined, something like:

    if (typeof(x) != "undefined") {
        // your variable exists
    }