Explain Codes LogoExplain Codes Logo

Javascript check if variable exists (is defined/initialized)

javascript
variable-checks
truthiness
type-coercion
Nikita BarsukovbyNikita Barsukov·Aug 14, 2024
TLDR

To verify that a variable is defined, use the typeof operator in a conditional:

if (typeof myVar !== "undefined") { // Turns out, myVar decided to exist }

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:

if (myVar != null) { // myVar ain't no null or undefined, yay! }

Looking for truthiness? Remember falsy values

When using checks like if (myVar), remember falsy values can throw you a curveball:

if (myVar) { // Heads up! This won't run for 0, '', false, null, or undefined }

Put your comparisons on a strict diet with ===

Prevent unintended cheeseburgers, I mean, type coercion with ===:

if (myVar === 0) { // Specifically check for diet version, I mean, value 0 }

Slicing and dicing strings

When dealing with strings, you might want to ensure they're not just space cadets:

if (myVar && typeof myVar === 'string' && myVar.trim()) { // myVar is a string and not a lazy space-monger }

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:

if ("myVar" in window) { // Turns out, myVar is a global citizen }

Scope: A tale of two contexts

Sometimes we stumble upon some really niche scenarios:

All's safe in undefined land

(function() { var undefined; // Hey look, an undefined in its natural habitat if (myVar !== undefined) { // Safe as houses! Our local undefined hasn't been tampered with } })();

Are we global yet? Accessing global scope variables

To refer to globally scoped variables, grab them by the window:

if (typeof window.myVar !== 'undefined') { // This myVar is a global superstar }

Don't fall for ReferenceErrors!

In dire straits where a variable may not even be declared, make sweet use of typeof:

if (typeof wildVariable !== 'undefined') { // Tamed! No ReferenceError, even if the wildVariable is a no-show }

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:

if ([]) { // Will always be as true as the sky is blue! }

Don't judge a variable by its cover: Strict type checking

Ensure you've got the right type along with existence:

if (typeof myVar === 'string' && myVar.trim()) { // myVar is a non-empty string that's all business, no fluff }

Meet null, the odd one out

Remember, null is a bit of an oddball:

if (typeof myVar === 'object') { // Surprise! This is also TRUE for null. }

Saving the day: A local undefined

Guard against mischievous global redefinitions of undefined:

(function(undefined) { if (myVar === undefined) { // Gotcha! Your global tampering won't work here, ha! } })(/* Nada, zilch, nothing here */);