Question

How to Check for undefined or null in JavaScript

javascriptjqueryvariablesnullundefined

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.

  • undefined usually means a value was not assigned or does not exist.
  • null usually 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.

Those are different:

undefined        // special value
"undefined"      // string containing text

That is why the check is wrong.

Correct checks include:

if (EmpName === undefined) {
  // value is undefined
}

or, if you want to handle both null and undefined together:

if (EmpName == null) {
  // value is null or undefined
}

This matters in real programming because many operations can return missing values:

  • DOM lookups
  • API responses
  • object properties
  • function arguments
  • optional configuration values

If you check incorrectly, your code may skip important logic or fail unexpectedly.

Mental Model

Think of JavaScript values like items in storage boxes:

  • A normal value like "Alice" means the box contains something useful.
  • null means the box is there, but someone deliberately left it empty.
  • undefined means the box was never filled, or maybe it was never set up at all.

Now imagine writing a label check:

  • Checking for undefined means: “Was nothing ever put here?”
  • Checking for null means: “Was this intentionally emptied?”
  • Checking == null means: “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.

Take Quiz

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:

  • 0
  • false
  • ""

Your example corrected

var empName = $("#esd-names #name").attr("class");

if (empName === undefined) {
  console.log("The class attribute does not exist.");
}

If you want to treat both null and undefined as missing:

var empName = $("#esd-names #name").attr("class");

if (empName == null) {
  console.log("The value is missing.");
}

Example with object properties

var user = {
  name: "Sam",
  age: null
};

console.log(user.email === undefined); // true
console.log(user.age === null);         // true
console.log(user.email == null);        // true
console.log(user.age == null);          // true

Explanation:

  • user.email was never defined, so it is undefined.
  • user.age was explicitly set to null.
  • == null matches both cases.

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

  1. JavaScript selects the element with id name inside #esd-names.
  2. jQuery tries to read its class attribute.
  3. The element exists, but no class attribute is present.
  4. jQuery returns undefined.
  5. The condition empName == null is evaluated.
  6. In JavaScript, undefined == null is true.
  7. The first branch runs and prints:
Missing class

Trace with a class present

If the HTML were:

<div id="esd-names">
  <div id="name" class="employee"></div>
</div>

Then:

  1. .attr("class") returns "employee".
  2. "employee" == null is false.
  3. The else branch runs.
  4. Output becomes:
Class is: employee

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

var role = $("#user-card").attr("data-role");
if (role === undefined) {
  console.log("Role attribute is missing");
}

5. Configuration defaults

function connect(timeout) {
  if (timeout == null) {
    timeout = 5000;
  }
  console.log("Timeout:", timeout);
}

This is especially useful when values might be optional.

Take Quiz

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.log("Saving", email);
}

Optional configuration

function createLogger(options) {
  options = options || {};

  if (options.prefix == null) {
    options.prefix = "[APP]";
  }

  return options.prefix;
}

Safer property access

Developers often combine null checks with optional chaining in modern JavaScript.

const city = user?.address?.city;

if (city == null) {
  console.log("City unavailable");
}

Important style note

Many teams prefer:

  • === undefined when they specifically mean only undefined
  • === null when they specifically mean only null
  • == null when they intentionally want to allow both

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:

  • 0
  • false
  • ""
  • NaN

That may be wrong.

Better

if (value == null) {
  console.log("Null or undefined only");
}

3. Confusing null and undefined

Broken assumption

if (value === null) {
  // assumes undefined will also match
}

It will not.

Fix

if (value == null) {
  // matches both null and undefined
}

4. Accessing properties before checking the parent object

Broken

console.log(user.address.city);

If user.address is undefined, this throws an error.

Better

if (user.address != null) {
  console.log(user.address.city);
}

Or in modern JavaScript:

console.log(user.address?.city);

5. Assuming DOM methods always return null

Different APIs behave differently.

  • Some DOM methods return null
  • Some libraries return undefined

Always check the documentation or inspect the actual returned value.

Comparisons

CheckWhat it meansMatches undefinedMatches nullMatches ""Matches 0
value === undefinedOnly undefinedYesNoNoNo
value === nullOnly nullNoYesNoNo
value == nullNull or undefinedYesYesNoNo
!valueAny falsy valueYesYesYesYes

undefined vs null

ValueMeaningTypical cause
undefinedNot assigned or missingmissing property, missing return, absent attribute
nullIntentionally emptyexplicit assignment like value = null

Strict equality vs loose equality

OperatorSafer for most comparisons?Useful here?
===YesYes, when checking one exact value
==Usually avoidYes, specifically for value == null

Use this rule of thumb:

  • Use === for exact checks
  • Use == null when you intentionally want both null and undefined
Take Quiz

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

  • undefined is a value, not a string.
  • "undefined" is text, not the same thing.
  • Use === undefined to check only for undefined.
  • Use === null to check only for null.
  • Use == null to check for both null and undefined.
  • Do not use !value unless you also want to catch 0, false, and empty strings.

jQuery example

var cls = $("#name").attr("class");

if (cls === undefined) {
  console.log("No class attribute");
}

Safe default pattern

var name = input == null ? "Guest" : input;

Common edge case

var count = 0;

if (!count) {
  console.log("This runs, even though count is a valid number");
}

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 NaN.

What does jQuery .attr() return if an attribute does not exist?

For a missing attribute, jQuery commonly returns undefined.

Can checking undefined cause an error?

Checking a declared variable is fine. Problems usually happen when code tries to use properties of a value that is null or undefined.

Is null == undefined true in JavaScript?

Yes. That is why value == null is a common shorthand for checking both.

Take Quiz

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

  1. Create a user object with some properties present, some set to null, and some missing.
  2. Check one property using === undefined.
  3. Check one property using === null.
  4. Check one property using == null.
  5. Print different messages based on what is missing.
  6. Include one example showing why !value can be misleading.
Take Quiz

Keep learning

Related questions

View more