How to check if a variable is initialized in Javascript?

How to check if a variable is initialized in my javascript code?

This test should return false for

var foo; 

and true for

 var foo = 5; 
+7
source share
2 answers
 if (foo === undefined) { /* not initialized */ } 

or for paranoid

 if (foo === (void) 0) 

This is something you can check directly in your JavaScript console. Just declare a variable and then use it in a (well, like) expression. What the console prints is a good hint of what you need to do.

+10
source

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 basic principles of jQuery JavaScript Basics really useful.

Hope this helps.

+5
source

All Articles