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;
3
  • if (foo == null)? or do you need to handle the case that it has been initialized to null? Commented Apr 16, 2012 at 20:59
  • possible duplicate of JavaScript check if variable exists - Which method is better? Commented Apr 16, 2012 at 21:02
  • actually, yes, i do need to differentiate from null thanks! Commented Apr 16, 2012 at 23:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

This works for functions as well. Comparing a non-initialized function with null (as in the answer) will throw an exception.
FYI, the jQuery Javascript 101 section was deleted (see github.com/jquery/learn.jquery.com/issues/117). It can still be read in the github history: github.com/jquery/learn.jquery.com/tree/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.