Question
How to Check If a Variable Exists in JavaScript
Question
In JavaScript, what is the correct way to check whether a variable has been initialized or is available to use?
Assume the variable could contain any type of value, such as a string, number, object, function, or another valid JavaScript value.
Common approaches include:
if (elem) {
// ...
}
or
if (typeof elem !== 'undefined') {
// ...
}
or
if (elem != null) {
// ...
}
Which approach is correct, and when should each one be used?
Short Answer
By the end of this page, you will understand the difference between checking whether a variable is defined, not null, or truthy in JavaScript. You will learn why these checks are not interchangeable, when typeof is safest, when != null is useful, and why if (elem) can accidentally reject valid values like 0, false, or "".
Concept
In JavaScript, "exists" can mean different things depending on context:
- Declared/defined: the variable name is known to JavaScript
- Initialized with a value: the variable currently holds something usable
- Not
nullorundefined: the value is present - Truthy: the value passes a boolean test in an
if
These are different checks.
1. if (elem) checks truthiness
if (elem) {
// runs only if elem is truthy
}
This does not mean “the variable exists”. It means the value is truthy.
These values are falsy in JavaScript:
false0-00n""nullundefinedNaN
So if elem is 0 or an empty string, if (elem) will fail even though the variable is valid and initialized.
2. typeof elem !== 'undefined' checks whether a variable is defined
if (typeof elem !== 'undefined') {
// elem is defined
}
This is the safest way to check whether an identifier exists without causing a ReferenceError, especially if the variable may not have been declared at all.
That makes it useful when:
- checking globals
- checking optional browser APIs
- checking whether a script loaded something
3. elem != null checks for both null and undefined
if (elem != null) {
// elem is neither null nor undefined
}
This is a common JavaScript pattern. Using loose inequality here is intentional:
null == undefinedistrue- so
elem != nullmeans “not null and not undefined”
This is useful when the variable is already declared and you only want to reject missing values, while still allowing values like:
0false""
Why this matters
In real programs, using the wrong check can cause bugs:
- rejecting a valid score of
0 - treating
falseas “missing” - crashing when checking a completely undeclared variable
- mixing up missing data with empty data
The best check depends on what you actually mean by “exists.”
Mental Model
Think of a variable like a labeled storage box.
typeof elem !== 'undefined'asks: Does this box label exist at all?elem != nullasks: Is there something in the box, instead of it being intentionally empty or missing?if (elem)asks: Does the content count as “yes” in a boolean decision?
That last question is different from the first two. A box containing 0 or false still has something in it, but JavaScript treats those values as falsy.
So before writing a condition, decide which question you really want to ask.
Syntax and Examples
Core checks
Check whether a variable is declared
if (typeof elem !== 'undefined') {
console.log('elem is defined');
}
Use this when elem may not exist at all.
Check whether a value is not null or undefined
if (elem != null) {
console.log('elem has a usable value');
}
Use this when the variable is already declared and you want to allow 0, false, and "".
Check whether a value is truthy
if (elem) {
console.log('elem is truthy');
}
Use this only when falsy values should be treated as “no”.
Example: same values, different results
const values = [undefined, null, 0, false, '', 'hello', 42, {}];
for (const value of values) {
console.log('Value:', value);
console.log('truthy check:', !!value);
console.log('!= null check:', value != null);
console.log('---');
}
What this shows
0,false, and""fail a truthy check- but they pass
!= null undefinedandnullfail both
Example: undeclared variable
if (typeof maybeLoadedLibrary !== 'undefined') {
console.log('Library is available');
}
This works even if maybeLoadedLibrary was never declared.
But this would throw an error:
if (maybeLoadedLibrary) {
console.log('Library is available');
}
If the variable does not exist, JavaScript raises a ReferenceError.
Step by Step Execution
Trace example
let elem = 0;
if (elem) {
console.log('truthy');
}
if (elem != null) {
console.log('not null or undefined');
}
if (typeof elem !== 'undefined') {
console.log('defined');
}
Step by step
1. let elem = 0;
A variable named elem is declared and given the value 0.
2. if (elem)
JavaScript converts elem to a boolean.
0is falsy- this block does not run
3. if (elem != null)
JavaScript checks whether elem is neither null nor undefined.
0 != nullistrue- this block runs
- output:
not null or undefined
4. if (typeof elem !== 'undefined')
JavaScript checks whether the variable is defined.
typeof elemis'number''number' !== 'undefined'istrue- this block runs
- output:
defined
Final output
not null or undefined
defined
This example shows why if (elem) is often too broad if 0 is a valid value.
Real World Use Cases
1. Optional browser APIs
if (typeof localStorage !== 'undefined') {
localStorage.setItem('theme', 'dark');
}
Use typeof when an API may or may not exist.
2. Form input values
if (userAge != null) {
saveAge(userAge);
}
Use != null if 0 is a valid input and should not be rejected.
3. Feature flags
if (config.enableLogging) {
log('Logging enabled');
}
A truthy check is fine when the value is intentionally boolean-like.
4. API response handling
if (response.data != null) {
renderData(response.data);
}
This accepts empty arrays, false, or 0 if those are valid returned values.
5. Third-party script detection
if (typeof analytics !== 'undefined') {
analytics.track('page_view');
}
This avoids errors when an external script fails to load.
Real Codebase Usage
In real projects, developers choose the check that matches the data rules.
Common patterns
Guard clause for required data
function printUsername(username) {
if (username == null) {
return 'Missing username';
}
return username;
}
This rejects only null and undefined.
Early return for unavailable globals
function savePreference(key, value) {
if (typeof localStorage === 'undefined') {
return;
}
localStorage.setItem(key, value);
}
Validation without rejecting valid falsy values
function setVolume(level) {
if (level == null) {
throw new Error('Volume level is required');
}
console.log('Volume set to', level);
}
This allows 0.
Boolean feature toggles
if (settings.debugMode) {
console.log('Debugging enabled');
}
Here, a truthy check is appropriate because the setting is meant to behave like a boolean.
Good practice
- Use
typeoffor possibly undeclared variables - Use
!= nullfor missing-value checks - Use direct truthy checks only when falsy values should be treated as disabled or absent
Common Mistakes
Mistake 1: Using if (value) when 0 is valid
Broken code
function showCount(count) {
if (count) {
console.log('Count:', count);
} else {
console.log('Missing count');
}
}
showCount(0);
This prints Missing count, which is wrong if 0 is a valid count.
Better
if (count != null) {
console.log('Count:', count);
}
Mistake 2: Accessing an undeclared variable directly
Broken code
if (someLibrary) {
someLibrary.init();
}
If someLibrary was never declared, this throws a ReferenceError.
Better
if (typeof someLibrary !== 'undefined') {
someLibrary.init();
}
Mistake 3: Confusing null with all falsy values
Broken code
if (!userInput) {
console.log('No input');
}
This treats "", 0, and false the same as null or undefined.
Better
if (userInput == null) {
console.log('Input is missing');
}
Mistake 4: Avoiding != null because it uses loose equality
Usually, loose equality is discouraged. But value != null is a widely accepted exception because it intentionally checks both null and undefined.
if (value != null) {
// valid pattern
}
Use it only for this specific purpose, not as a general replacement for strict equality.
Mistake 5: Assuming declared means initialized usefully
let item;
if (typeof item !== 'undefined') {
console.log('Defined');
}
This is true, but item is still undefined as a value. The variable exists, but it does not yet hold useful data.
If you care about the value, use:
if (item != null) {
console.log('Has real value');
}
Comparisons
| Check | What it means | Safe for undeclared variable? | Accepts 0, false, ""? | Best use |
|---|---|---|---|---|
if (elem) | value is truthy | No | No | Boolean-like conditions |
elem != null | value is not null or undefined | No | Yes | Missing-value checks |
typeof elem !== 'undefined' | variable is declared/defined | Yes | Yes | Possibly undeclared identifiers |
Quick comparison examples
let a = 0;
let b = null;
if (a) console.log('a truthy');
if (a != null) console.log('a present');
if (typeof a !== 'undefined') console.log('a defined');
Output:
a present
a defined
For b:
if (b) console.log('b truthy');
if (b != null) console.log('b present');
if (typeof b !== 'undefined') console.log('b defined');
Output:
b defined
This shows that null is still a defined value in a declared variable.
Cheat Sheet
Quick rules
- Use
typeof x !== 'undefined'whenxmight not be declared at all - Use
x != nullwhen you want to reject onlynullandundefined - Use
if (x)only when falsy values should count as “no”
Falsy values
false
0
-0
0n
''
null
undefined
NaN
Safe patterns
typeof x !== 'undefined'
x != null
x == null // true for null or undefined
Be careful
if (x)
This rejects:
0false''NaN
Common intent → correct check
| Intent | Recommended check |
|---|---|
| Variable may not exist at all | typeof x !== 'undefined' |
| Value must not be missing | x != null |
| Value must be truthy | if (x) |
| Check for null or undefined | x == null |
Remember
defined is not the same as truthy.
null is not the same as undeclared.
0 and false are valid values, even though they are falsy.
FAQ
What is the safest way to check if a variable exists in JavaScript?
Use typeof variable !== 'undefined' if the variable might not have been declared at all.
Why is if (value) not enough?
Because it checks truthiness, not existence. Valid values like 0, false, and "" will fail.
When should I use value != null?
Use it when the variable is already declared and you want to allow falsy values while rejecting only null and undefined.
Is value != null considered good JavaScript?
Yes, for this specific case. It is a common and intentional pattern for checking both null and undefined at once.
What happens if I access an undeclared variable directly?
JavaScript throws a ReferenceError. That is why typeof undeclaredVar is safer.
Does typeof x !== 'undefined' mean the value is usable?
Not always. It only means the variable is defined. It could still hold undefined, null, or another unwanted value depending on your logic.
Should I use strict equality instead of != null?
If you want to check both null and undefined, != null is shorter and idiomatic. If you want to distinguish them, use strict checks like x === null or x === undefined.
Mini Project
Description
Build a small JavaScript utility that classifies values in three ways: whether they are defined, whether they are null/undefined, and whether they are truthy. This project is useful because real applications often need to distinguish between missing values and valid falsy values such as 0 or false.
Goal
Create a function that tests a list of values and reports how each JavaScript check behaves.
Requirements
- Create a function that accepts a value and returns whether it is truthy.
- Include a check that reports whether the value is
nullorundefined. - Test the function with values such as
undefined,null,0,false,"", and"hello". - Print readable results to the console.
- Include one example showing
typeofused with a possibly undeclared variable.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.