Question
How can I correctly determine whether a variable in JavaScript is undefined or null?
For example, I have code like this:
var EmpName = $("div#esd-names div#name").attr("class");
if (EmpName == "undefined") {
// DO SOMETHING
}
And this HTML:
<div id="esd-names">
<div id="name"></div>
</div>
However, when I try this approach, execution does not behave as expected. What is the correct way to check whether the value returned is undefined or null?
Short Answer
By the end of this page, you will understand the difference between undefined and null in JavaScript, how to test for each one correctly, when to use == null, when to use strict checks, and why comparing to the string "undefined" is incorrect.
Concept
In JavaScript, undefined and null are special values that both represent “no useful value,” but they are not the same thing.
undefinedusually means a value was not assigned or does not exist.nullusually means a value was intentionally set to “nothing.”
In your example, this line:
var EmpName = $("div#esd-names div#name").attr("class");
asks jQuery for the class attribute of the #name element. Since the element exists but has no class attribute, jQuery returns undefined.
The important detail is this:
if (EmpName == "undefined")
checks whether EmpName is equal to the string "undefined", not the special JavaScript value undefined.
Mental Model
Think of JavaScript values like items in storage boxes:
- A normal value like
"Alice"means the box contains something useful. nullmeans the box is there, but someone deliberately left it empty.undefinedmeans the box was never filled, or maybe it was never set up at all.
Now imagine writing a label check:
- Checking for
undefinedmeans: “Was nothing ever put here?” - Checking for
nullmeans: “Was this intentionally emptied?” - Checking
== nullmeans: “Is this missing in either of those two common ways?”
Comparing to "undefined" is like checking whether the box contains a note that literally says undefined, instead of checking whether the box is actually empty.
Syntax and Examples
Core syntax
Check only for undefined
if (value === undefined) {
console.log("Value is undefined");
}
Check only for null
if (value === null) {
console.log("Value is null");
}
Check for either null or undefined
if (value == null) {
console.log("Value is null or undefined");
}
This is one of the few common cases where loose equality == is intentionally useful, because:
null == undefined // true
but it does not match other falsy values like:
Step by Step Execution
Consider this example:
var empName = $("#esd-names #name").attr("class");
if (empName == null) {
console.log("Missing class");
} else {
console.log("Class is:", empName);
}
Step-by-step
- JavaScript selects the element with id
nameinside#esd-names. - jQuery tries to read its
classattribute. - The element exists, but no
classattribute is present. - jQuery returns
undefined. - The condition
empName == nullis evaluated. - In JavaScript,
undefined == nullistrue. - The first branch runs and prints:
Missing class
Trace with a class present
Real World Use Cases
Checking for undefined and null is common in many practical situations.
1. Reading optional object properties
if (user.middleName == null) {
console.log("No middle name provided");
}
2. Handling API data
APIs may omit a field entirely (undefined) or send it as null.
if (response.data.address == null) {
console.log("Address is unavailable");
}
3. Validating function arguments
function greet(name) {
if (name == null) {
name = "Guest";
}
console.log("Hello, " + name);
}
4. Checking DOM attributes
Real Codebase Usage
In real codebases, developers usually do not check for undefined and null randomly. They use them as part of clear patterns.
Guard clauses
Stop early if required data is missing.
function renderUser(user) {
if (user == null) {
return;
}
console.log(user.name);
}
Default values
Provide a fallback when a value is missing.
function getDisplayName(name) {
return name == null ? "Anonymous" : name;
}
Validation before using data
function saveEmail(email) {
if (email == null) {
throw new Error("Email is required");
}
console.(, email);
}
Common Mistakes
1. Comparing to the string "undefined"
This is the mistake from the original question.
Broken
if (empName == "undefined") {
// wrong
}
Correct
if (empName === undefined) {
// correct
}
2. Using a falsy check when you only mean nullish values
Problem
if (!value) {
console.log("Missing");
}
This also matches:
0false""NaN
That may be wrong.
Better
if (value == null) {
.();
}
Comparisons
| Check | What it means | Matches undefined | Matches null | Matches "" | Matches 0 |
|---|---|---|---|---|---|
value === undefined | Only undefined | Yes | No | No | No |
value === null | Only null | No | Yes | No | No |
value == null | Null or undefined | Yes | Yes |
Cheat Sheet
// exact checks
value === undefined
value === null
// check for either null or undefined
value == null
// avoid if you only mean null/undefined
!value
Quick rules
undefinedis a value, not a string."undefined"is text, not the same thing.- Use
=== undefinedto check only for undefined. - Use
=== nullto check only for null. - Use
== nullto check for both null and undefined. - Do not use
!valueunless you also want to catch0,false, and empty strings.
jQuery example
var cls = $("#name").attr("class");
if (cls === undefined) {
console.log("No class attribute");
}
Safe default pattern
FAQ
What is the difference between undefined and null in JavaScript?
undefined usually means a value is missing or was never assigned. null usually means a value was intentionally set to empty.
Should I use === undefined or == null?
Use === undefined if you want only undefined. Use == null if you want both null and undefined.
Why is "undefined" wrong?
Because it is a string. JavaScript's undefined is a special value, not text.
Does !value mean the same as value == null?
No. !value also matches 0, false, "", and .
Mini Project
Description
Build a small profile-reader script that checks whether optional user data exists before displaying it. This demonstrates how to safely handle missing values from objects and DOM attributes without confusing undefined, null, and other falsy values.
Goal
Create a script that prints sensible fallback messages when profile fields are missing or intentionally empty.
Requirements
- Create a user object with some properties present, some set to
null, and some missing. - Check one property using
=== undefined. - Check one property using
=== null. - Check one property using
== null. - Print different messages based on what is missing.
- Include one example showing why
!valuecan be misleading.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.