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
, orvar
. - Use
null
to signal “empty on purpose”. - Use
===
ortypeof
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
, orvar
.// Bad: total = 10; // ReferenceError in strict mode // Good: let total = 10;
Quick Checks
What are you checking? | Example Code |
---|---|
Is undefined | typeof x === "undefined" |
Is null | x === null |
Is null or undefined | x == null (rarely) |
Might be undeclared | typeof 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>;
Value | Meaning | Example Use |
---|---|---|
undefined | Not yet loaded | Initial state |
null | Loaded, no data | API 404 / reset |
valid object | Loaded, data | Show UI content |
Further Reading
Last updated on