Javascript check if variable exists (is defined/initialized)
To verify that a variable is defined, use the typeof
operator in a conditional:
The typeof
check avoids the booby trap of ReferenceErrors if myVar forgot to declare itself.
Gotchas in existence checks
Beyond undefined: Checking for non-null
Occasionally, just checking for undefined isn't enough. Here's a way to check for both null
and undefined
:
Looking for truthiness? Remember falsy values
When using checks like if (myVar)
, remember falsy values can throw you a curveball:
Put your comparisons on a strict diet with ===
Prevent unintended cheeseburgers, I mean, type coercion with ===
:
Slicing and dicing strings
When dealing with strings, you might want to ensure they're not just space cadets:
Does it belong to the global village? A story of global variables
For proper global variable checks, show them who's boss with "variable" in window
:
Scope: A tale of two contexts
Sometimes we stumble upon some really niche scenarios:
All's safe in undefined land
Are we global yet? Accessing global scope variables
To refer to globally scoped variables, grab them by the window:
Don't fall for ReferenceErrors!
In dire straits where a variable may not even be declared, make sweet use of typeof
:
Truthiness, falsiness and other surprises
Is it a bird? Is it a plane? No, it's truthy!
Remember, empty arrays []
, or empty objects {}
, still wear the truthy cape:
Don't judge a variable by its cover: Strict type checking
Ensure you've got the right type along with existence:
Meet null, the odd one out
Remember, null
is a bit of an oddball:
Saving the day: A local undefined
Guard against mischievous global redefinitions of undefined
:
Was this article helpful?