8

How do I test if a variable in my javascript code is initialized?

This test should return false for

var foo;

and true for

var foo = 5;
Pointy
  • 405,095
  • 59
  • 585
  • 614
John Hoffman
  • 17,857
  • 20
  • 58
  • 81
  • if `(foo == null)?` or do you need to handle the case that it has been initialized to null? – Aidanc Apr 16 '12 at 20:59
  • possible duplicate of [JavaScript check if variable exists - Which method is better?](http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-which-method-is-better) – James Montagne Apr 16 '12 at 21:02
  • actually, yes, i do need to differentiate from null thanks! – John Hoffman Apr 16 '12 at 23:16

2 Answers2

13
if (foo === undefined) { /* not initialized */ }

or for the paranoid

if (foo === (void) 0)

This is the sort of thing that you can test right in your JavaScript console. Just declare a variable and then use it in (well, as) an expression. What the console prints is a good hint to what you need to do.

Pointy
  • 405,095
  • 59
  • 585
  • 614
7

Using the typeof operator you can use the following test:

if (typeof foo !== 'undefined') {
    // foo has been set to 5
}
else {
    // foo has not been set
}

I find the jQuery fundamentals JavaScript Basics chapter really useful.

I hope this helps.

Woody
  • 373
  • 2
  • 9
  • This works for functions as well. Comparing a non-initialized function with null (as in the answer) will throw an exception. – f2lollpll Aug 20 '13 at 13:11