Question

Checking for null, undefined, and empty values in JavaScript

javascriptnullcomparisonundefined

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:

  • undefined means a value was not provided or not assigned.
  • null means a value was intentionally set to “no value”.
  • "" is an empty string.
  • [] is an empty array.
  • 0 is a valid number, but it is falsy.
  • false is 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:

  • undefined
  • null
  • ""
  • []

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 you
  • null = 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 inside
  • 0 = a number container holding zero, which is still a real value
  • false = 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.

Take Quiz

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 == null is a common JavaScript shortcut.
  • It is true for both null and undefined.
  • It does not match "", 0, or false.

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 == null is checked.
  • undefined == null is true.
  • JavaScript stops evaluating because || only needs one true condition.
  • Result: true

Case 2: isEmpty(" ")

  • value == null is false.
  • typeof value === "string" is true.
  • value.trim() becomes "".
  • "" === "" is true.
  • Result: true

Case 3: isEmpty([])

  • value == null is false.
  • typeof value === "string" is false.
  • Array.isArray(value) is true.
  • value.length === 0 is true.
  • Result: true

Case 4: isEmpty(0)

  • value == null is false.
  • typeof value === "string" is false.
  • Array.isArray(value) is false.
  • 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.

Take Quiz

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:

  • 0 becomes empty
  • false becomes empty
  • "" becomes empty
  • null and undefined become 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.length throws an error
  • undefined.length throws 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

CheckWhat it matchesGood forRisk
value == nullnull and undefinedMissing valuesUses loose equality intentionally
value === nullOnly nullExact null checksMisses undefined
value === undefinedOnly undefinedExact undefined checksMisses null
!valueAll falsy valuesQuick truthy/falsy logicWrong if 0 or false are valid
value.length === 0Empty strings or arrays with lengthKnown string/array valuesUnsafe on unknown types
typeof value === "string" && value.trim() === ""Empty or whitespace-only stringsUser text inputOnly for strings
Array.isArray(value) && value.length === 0Empty arraysLists and collectionsOnly for arrays

null/undefined vs empty string

ValueMeaning
undefinedNot assigned or missing
nullIntentionally no value
""String exists, but has no characters
" "String has only spaces

|| vs ??

OperatorFalls back onExample
``
??Only null or undefined0 ?? 10 gives 0

Use ?? when 0, false, or "" should remain valid.

Take Quiz

Cheat Sheet

Quick checks

value == null
  • True for null and undefined
  • 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 !value if 0 or false are valid.
  • Avoid reading .length unless you know the value is a string or array.
  • Use == null as a deliberate shortcut for null or undefined.
  • 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.

Take Quiz

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

  1. Create helper functions for nullish values, blank strings, and empty arrays.
  2. Validate an object with fields such as name, email, age, and tags.
  3. Treat null, undefined, blank strings, and empty arrays as invalid where appropriate.
  4. Do not treat 0 or false as automatically empty.
  5. Output a list of validation errors for invalid fields.
Take Quiz

Keep learning

Related questions

View more