Question
Checking for null, undefined, and empty values in JavaScript
Question
In JavaScript, is there a standard way to check whether a variable actually has a usable value and is not undefined, null, or empty?
For example, I have this function and want to know whether it correctly covers all cases:
function isEmpty(val) {
return val === undefined || val == null || val.length <= 0;
}
I want to understand whether there is a universal built-in solution, and if not, what the correct approach is for checking values like empty strings, missing variables, or empty arrays.
Short Answer
By the end of this page, you will understand the difference between undefined, null, and “empty” values in JavaScript, why there is no single built-in function that handles every case, and how to write safe checks for strings, arrays, and general values.
Concept
JavaScript does not have one universal built-in function that means “this value is valid and not blank” for every type.
That is because these checks represent different ideas:
undefinedmeans a value was not provided or not assigned.nullmeans a value was intentionally set to “no value”.""is an empty string.[]is an empty array.0is a valid number, but it is falsy.falseis a valid boolean, but it is also falsy.
These values are not interchangeable, so JavaScript leaves it up to you to decide what “empty” means in your program.
For example:
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean(false)); // false
console.log(Boolean([])); // true
console.log(Boolean({})); // true
This matters because a simple truthy/falsy check like:
if (!value) {
// value is falsy
}
will treat 0 and false as “empty”, which is often wrong.
Your original function also has a limitation:
function isEmpty(val) {
return val === undefined || val == null || val.length <= 0;
}
It works for some values, such as:
undefinednull""[]
But it does not safely describe all JavaScript values, because many values do not have a length property, such as numbers, booleans, plain objects, and functions.
So the key lesson is:
- There is no single universal empty check.
- You should check based on the type of value and what your application considers valid.
Mental Model
Think of JavaScript values as different kinds of containers:
undefined= no container was handed to younull= a container was handed to you, but it was deliberately left empty""= a text container with no characters inside[]= a list container with no items inside0= a number container holding zero, which is still a real valuefalse= a yes/no container holding “no”, which is still a real value
The mistake beginners often make is treating all “small” or “empty-looking” values as the same thing. But JavaScript sees them differently.
A better mental model is:
First ask: what type of value am I expecting? Then ask: what counts as empty for that type?
That approach leads to safer code than trying to force one universal check on every possible value.
Syntax and Examples
The most common checks are small and specific.
1. Check for null or undefined
if (value == null) {
console.log("Value is null or undefined");
}
Why this works:
value == nullis a common JavaScript shortcut.- It is true for both
nullandundefined. - It does not match
"",0, orfalse.
2. Check for an empty string
if (value === "") {
console.log("Value is an empty string");
}
If you also want to treat spaces as empty:
if (typeof value === "string" && value.trim() === "") {
console.log("String is blank");
}
3. Check for an empty array
if (Array.isArray(value) && value.length === 0) {
console.log("Array is empty");
}
4. A safer reusable helper
function isNullOrUndefined(value) {
return value == null;
}
function isBlankString(value) {
return typeof value === "string" && value.trim() === "";
}
function isEmptyArray(value) {
return Array.isArray(value) && value.length === 0;
}
5. A broader helper if your app defines “empty” this way
function isEmpty(value) {
return (
value == null ||
(typeof value === "string" && value.trim() === "") ||
(Array.isArray(value) && value.length === 0)
);
}
Example usage:
console.log(isEmpty(undefined)); // true
console.log(isEmpty(null)); // true
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // true
console.log(isEmpty([])); // true
console.log(isEmpty([1, 2])); // false
console.log(isEmpty(0)); // false
console.log(isEmpty(false)); // false
This is usually better than checking .length on every value.
Step by Step Execution
Consider this example:
function isEmpty(value) {
return (
value == null ||
(typeof value === "string" && value.trim() === "") ||
(Array.isArray(value) && value.length === 0)
);
}
console.log(isEmpty(undefined));
console.log(isEmpty(" "));
console.log(isEmpty([]));
console.log(isEmpty(0));
Here is what happens step by step.
Case 1: isEmpty(undefined)
value == nullis checked.undefined == nullistrue.- JavaScript stops evaluating because
||only needs one true condition. - Result:
true
Case 2: isEmpty(" ")
value == nullisfalse.typeof value === "string"istrue.value.trim()becomes""."" === ""istrue.- Result:
true
Case 3: isEmpty([])
value == nullisfalse.typeof value === "string"isfalse.Array.isArray(value)istrue.value.length === 0istrue.- Result:
true
Case 4: isEmpty(0)
value == nullisfalse.typeof value === "string"isfalse.Array.isArray(value)isfalse.- No condition matches.
- Result:
false
This is good because 0 is usually a valid value, not an empty one.
Real World Use Cases
This kind of checking appears everywhere in JavaScript projects.
Form validation
function validateName(name) {
return !(typeof name === "string" && name.trim() === "");
}
Used when users submit signup forms, profile edits, or search boxes.
API response handling
if (response.data == null) {
throw new Error("Missing API data");
}
Useful when a backend may return null or omit a field.
Optional user input
if (tags == null || tags.length === 0) {
console.log("No tags provided");
}
Helpful for filters, categories, selected items, or uploaded files.
Config defaults
function getPageSize(pageSize) {
return pageSize == null ? 20 : pageSize;
}
This keeps 0 from being overwritten unless you explicitly want that behavior.
Data cleaning scripts
const cleaned = values.filter(value => value != null);
Often used before saving data, transforming CSV rows, or building reports.
Real Codebase Usage
In real projects, developers usually avoid one giant “universal empty” rule and instead use small targeted checks.
Guard clauses
A guard clause exits early when required data is missing.
function printUserName(user) {
if (user == null) return;
if (typeof user.name !== "string" || user.name.trim() === "") return;
console.log(user.name);
}
Validation helpers
Teams often create utility functions with very clear names.
export function isNil(value) {
return value == null;
}
export function isNonEmptyString(value) {
return typeof value === "string" && value.trim() !== "";
}
These names are clearer than a vague isEmpty() that tries to do too much.
Early returns in APIs and controllers
function createPost(title) {
if (typeof title !== "string" || title.trim() === "") {
return { error: "Title is required" };
}
return { success: true };
}
Filtering nullish values
const values = ["a", null, "b", undefined];
const result = values.filter(value => value != null);
console.log(result); // ["a", "b"]
Default values with nullish coalescing
const username = inputName ?? "Guest";
This only falls back for null or undefined, not for "", 0, or false.
That is often exactly what production code wants.
Common Mistakes
1. Treating all falsy values as empty
Broken example:
if (!value) {
console.log("Empty");
}
Problem:
0becomes emptyfalsebecomes empty""becomes emptynullandundefinedbecome empty
Fix:
Use a more specific check.
if (value == null) {
console.log("Null or undefined only");
}
2. Accessing .length on values that may not have it
Broken example:
function isEmpty(value) {
return value.length === 0;
}
Problem:
null.lengththrows an errorundefined.lengththrows an error- numbers and booleans do not have
length
Fix:
function isEmptyArray(value) {
return Array.isArray(value) && value.length === 0;
}
3. Using === null when undefined is also possible
Broken example:
if (value === null) {
console.log("Missing");
}
Problem:
- Misses
undefined
Fix:
if (value == null) {
console.log("Null or undefined");
}
4. Forgetting to trim strings
Broken example:
if (value === "") {
console.log("Blank");
}
Problem:
- A string like `
Comparisons
Common ways to check values
| Check | What it matches | Good for | Risk |
|---|---|---|---|
value == null | null and undefined | Missing values | Uses loose equality intentionally |
value === null | Only null | Exact null checks | Misses undefined |
value === undefined | Only undefined | Exact undefined checks | Misses null |
!value | All falsy values | Quick truthy/falsy logic | Wrong if 0 or false are valid |
value.length === 0 | Empty strings or arrays with length | Known string/array values | Unsafe on unknown types |
typeof value === "string" && value.trim() === "" | Empty or whitespace-only strings | User text input | Only for strings |
Array.isArray(value) && value.length === 0 | Empty arrays | Lists and collections | Only for arrays |
null/undefined vs empty string
| Value | Meaning |
|---|---|
undefined | Not assigned or missing |
null | Intentionally no value |
"" | String exists, but has no characters |
" " | String has only spaces |
|| vs ??
| Operator | Falls back on | Example |
|---|---|---|
| ` | ` | |
?? | Only null or undefined | 0 ?? 10 gives 0 |
Use ?? when 0, false, or "" should remain valid.
Cheat Sheet
Quick checks
value == null
- True for
nullandundefined - False for
"",0,false,[],{}
typeof value === "string" && value.trim() === ""
- True for empty or whitespace-only strings
Array.isArray(value) && value.length === 0
- True for empty arrays
Safer helper
function isEmpty(value) {
return (
value == null ||
(typeof value === "string" && value.trim() === "") ||
(Array.isArray(value) && value.length === 0)
);
}
Rules to remember
- There is no built-in universal
isEmpty()in JavaScript. - “Empty” depends on the type.
- Avoid
!valueif0orfalseare valid. - Avoid reading
.lengthunless you know the value is a string or array. - Use
== nullas a deliberate shortcut fornullorundefined. - Use
??for defaults when only nullish values should trigger the fallback.
Common edge cases
Boolean([]) // true
Boolean({}) // true
Boolean(0) // false
Boolean(false)// false
Boolean("") // false
Empty arrays and empty objects are truthy in JavaScript.
FAQ
Is there a built-in JavaScript isEmpty() function?
No. JavaScript does not provide a universal built-in isEmpty() for all value types.
What is the best way to check for null or undefined?
Use:
value == null
This is a common shorthand that matches both null and undefined.
Should I use !value to check if something is empty?
Only if you truly want all falsy values to count as empty. It will also match 0 and false, which may be valid values.
How do I check if a string is empty or only spaces?
Use:
typeof value === "string" && value.trim() === ""
How do I check if an array is empty?
Use:
Array.isArray(value) && value.length === 0
Why is [] truthy in JavaScript?
Because arrays are objects, and objects are truthy in JavaScript, even when they contain no items.
Is null the same as undefined?
No. They are different values, but value == null is designed to match both.
What should I do in real projects?
Write specific checks based on the type you expect: string, array, object, number, or optional value.
Mini Project
Description
Build a small validation utility for a form-like input object. This project demonstrates how to distinguish between missing values, blank strings, and empty arrays without accidentally rejecting valid values such as 0 or false.
Goal
Create a reusable JavaScript validator that checks user input fields safely and reports which fields are missing or empty.
Requirements
- Create helper functions for nullish values, blank strings, and empty arrays.
- Validate an object with fields such as
name,email,age, andtags. - Treat
null,undefined, blank strings, and empty arrays as invalid where appropriate. - Do not treat
0orfalseas automatically empty. - Output a list of validation errors for invalid fields.
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.