How to compare variables to undefined, if I don’t know whether they exist?

JavascriptUndefined

Javascript Problem Overview


In JavaScript you can declare a variable and if it’s undefined, you can check variable == undefined; I know that, but how can you compare a value that you don’t know yet if it’s in memory?

For example, I have a class which is created when the user clicks a button. Before this, the class is undefined — it doesn’t exist anywhere; how can I compare it?

Is there a way without using trycatch?

Javascript Solutions


Solution 1 - Javascript

The best way is to check the type, because undefined/null/false are a tricky thing in JS. So:

if(typeof obj !== "undefined") {
    // obj is a valid variable, do something here.
}

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

Solution 2 - Javascript

if (obj === undefined)
{
    // Create obj
}

If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.

Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.

Solution 3 - Javascript

if (document.getElementById('theElement')) // do whatever after this

For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:

if (blah) ...

do:

if (window.blah) ...

Solution 4 - Javascript

!undefined is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:

if(<object or variable>) {
     //take actions if object is not undefined
} else {
     //take actions if object is undefined
}

Solution 5 - Javascript

if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...

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
QuestionncubicaView Question on Stackoverflow
Solution 1 - JavascriptMakram SalehView Answer on Stackoverflow
Solution 2 - JavascriptTimmyView Answer on Stackoverflow
Solution 3 - JavascriptDelan AzabaniView Answer on Stackoverflow
Solution 4 - JavascriptMr.HuntView Answer on Stackoverflow
Solution 5 - JavascriptThevsView Answer on Stackoverflow