Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a variable in Javascript is initialized?

Tags:

javascript

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;
like image 678
John Hoffman Avatar asked Apr 16 '12 20:04

John Hoffman


2 Answers

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.

like image 189
Pointy Avatar answered Oct 12 '22 00:10

Pointy


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.

like image 25
Woody Avatar answered Oct 11 '22 22:10

Woody