Skip to Content
BlogJavaScriptJavaScript: null vs undefined vs undeclared (With Examples & Best Practices)

JavaScript: null vs undefined vs Undeclared (Quick Guide)

Understand the difference between null, undefined, and undeclared variables in JavaScript. Avoid common pitfalls and write safer code.

What’s the Difference?

  • undefined: Variable is declared but not assigned a value.

    let foo; console.log(foo); // undefined
  • null: You assign this to mean “no value” or “empty on purpose”.

    const bar = null;
  • undeclared: Variable never declared (throws error in strict mode).

    "use strict"; x = 5; // ReferenceError: x is not defined

Best Practices for JavaScript Variables

  • Always declare variables with let, const, or var.
  • Use null to signal “empty on purpose”.
  • Use === or typeof for checks, not ==.
  • Use linters or TypeScript to catch undeclared variables.

When to Use Each (with Examples)

  • undefined: For variables declared but not yet assigned (default JS behavior).

    let count; // count is undefined
  • null: When you want to intentionally clear a value or signal “empty on purpose”.

    let user = getUser(); if (!user) user = null; // explicitly no user
  • Undeclared: Avoid! Always declare with let, const, or var.

    // Bad: total = 10; // ReferenceError in strict mode // Good: let total = 10;

Quick Checks

What are you checking?Example Code
Is undefinedtypeof x === "undefined"
Is nullx === null
Is null or undefinedx == null (rarely)
Might be undeclaredtypeof x === "undefined"

React Example: null vs undefined

In React, you might encounter both null and undefined when dealing with state or props. Here’s a quick example:

const [user, setUser] = useState(); // undefined by default useEffect(() => { fetch(`/api/users/${id}`) .then((res) => { if (res.status === 404) return setUser(null); // not found return res.json().then((data) => setUser(data)); }) .catch(() => setError("Failed to fetch")); }, [id]); // UI Logic if (user === undefined) return <p>Loading...</p>; if (user === null) return <p>User not found.</p>; return <p>Hello, {user.name}!</p>;
ValueMeaningExample Use
undefinedNot yet loadedInitial state
nullLoaded, no dataAPI 404 / reset
valid objectLoaded, dataShow UI content

Further Reading

Last updated on