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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With