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
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
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 nor .
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.);
}
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 ();
}
.(, level);
}
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 .
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 |
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
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?
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
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.