116

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
ncubica
  • 8,169
  • 9
  • 54
  • 72

5 Answers5

214

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.

Makram Saleh
  • 8,613
  • 4
  • 27
  • 44
  • 14
    make that `if(typeof obj !== "undefined") {}` and it's perfect (notice second equals sign) – raveren Jun 11 '12 at 14:33
  • 2
    What is the trick stuff? Why not only doring a direct comparison like Timmys answer? – Alex Feb 09 '16 at 13:43
  • 12
    You can just use `obj !== undefined` now. `undefined` used to be mutable, like `undefined = 1234` what would cause interesting results. But after Ecmascript 5, it's not writable anymore, so we can use the simpler version. http://www.codereadability.com/how-to-check-for-undefined-in-javascript/ – Bruno Buccolo Mar 15 '16 at 20:50
  • Beware that `obj` may be `null` or `false`, in which case my guess is that you wouldn't want to execute such code either. Of course there can be exceptions and special cases. `null`, `false`, `undefined` are all "falsy" values and they can be easily evaluated like this: `if (obj) { ... }` – Amy Pellegrini Jul 25 '16 at 15:42
  • @AmyPellegrini my example above will still work, because typeof will not fire an error even if the variable is null or false. That's the beauty of it. – Makram Saleh Jul 28 '16 at 11:47
  • @MakramSaleh it will not fire an error, but it will pass evaluation as "true" if `obj === null` or `obj === false`. Just a warning, of course the context and the content inside `if` will determine if the code fails or not. – Amy Pellegrini Jul 28 '16 at 16:58
  • 2
    @Raveren you don't need a type enforcing comparison, both side are already strings and type inference won't happen – Hugh Wood Aug 22 '16 at 10:05
  • let options = null undefined > typeof options 'object' if the value is null we have a problem – PirateApp Oct 06 '18 at 11:03
79
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.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Timmy
  • 1,445
  • 11
  • 3
2
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) ...
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
0

!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
}
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Mr.Hunt
  • 4,833
  • 2
  • 22
  • 28
  • thanks for you time but, I this case if you try to compare an undeclared variable you are going get a error throw saying you haven't declare the variable... so is impossible to compare it... so is why you need to transform the type of the variable in a string format in a way to compare it successfully example if( type of myundeclaredvarible == "undefined") //do something best nahum @Rahul Panday – ncubica Jul 06 '11 at 20:06
  • you already edited the last one is quite cool never seen before thanks :) – ncubica Nov 15 '11 at 19:52
-2
if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...
Thevs
  • 3,189
  • 2
  • 20
  • 32
  • 1
    obj may very well exist but be false or 0. – andig Jun 19 '15 at 07:23
  • Regular object cannot be just `false` or `0`. It should contain pairs of `key -> value`, or empty, or undefined, or null. – Thevs Jun 20 '15 at 06:15
  • That was not the question though. Just because you call a variable obj it may still be anything imho. – andig Jun 21 '15 at 09:03
  • `'I have a class which is created when the user clicks a button. Before this the class is undefined, it doesn't exist anywhere so how can I compare it?` - that was a question. – Thevs Jun 22 '15 at 05:36
  • -1. Question includes `you can check variable == undefined`. `!obj` is even is worse than `obj == undefined`. Compare `!NaN` (true) vs. `NaN == undefined` (false) – Tino Jan 25 '21 at 17:31