Question

I find myself checking to see if javascript elements exist a lot using:

if (typeof elem == "undefined")
  // Do something

I want to create a function so I can reduce code repetition.

if (exists(elem))

Here is the function I created:

if (typeof exists == 'undefined') {
    function exists (e)
    {
        if (typeof e == "undefined")
            return false;
        return true;
    }
}

The problem is the variable is undefined before it goes through the function. It generates a javascript error. How do I create a function to handle this?

Was it helpful?

Solution

"The problem is the variable is undefined before it goes through the function. It generates a javascript error."

By "undefined", I assume you mean "undeclared", therefore causing a ReferenceError.

If so, you would need to test to see if it exists before you pass it to the function, which makes the function rather pointless.

Rather than trying to create a function to test for undeclared variables, simply declare them before using them.

IMO, typeof x === 'undefined' is an ugly hack that shouldn't be necessary. You should consider the ReferenceError to be a friend that is telling you something needs fixing. The typeof hack prevents your friend from telling you what's going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top