JAVASCRIPT

JavaScript undefined: Syntax, Usage, and Examples

JavaScript undefined is a special primitive value that means “this variable or property has no value assigned yet.”

You see undefined JavaScript values everywhere: in uninitialized variables, missing object properties, and function calls with too few arguments.

How to Use undefined in JavaScript

Most of the time, you don’t “use” JavaScript undefined by assigning it directly. The engine gives you undefined automatically when something exists but does not yet have a value.

Uninitialized Variables

When you declare a variable without assigning a value, JavaScript sets it to undefined:

let count;
console.log(count); // undefined

The variable count exists, but no value was stored in it. That is the default undefined JavaScript state.

Missing Object Properties

Accessing a property that doesn’t exist returns undefined instead of throwing an error:

const user = { name: "Nia" };

console.log(user.name); // "Nia"
console.log(user.age);  // undefined

The user object simply has no age property. undefined shows that the lookup completed but found nothing.

Missing Function Arguments

Function parameters that don’t receive an argument also become undefined:

function greet(name, greeting) {
  console.log(`${greeting}, ${name}!`);
}

greet("Alex"); // greeting is undefined

Here, greeting has no value because the function was called with one argument instead of two.

Functions Without a Return

If a function finishes without hitting a return statement, it returns undefined:

function logMessage(message) {
  console.log(message);
}

const result = logMessage("Hello");
console.log(result); // undefined

This is a common source of subtle bugs, so recognizing JavaScript undefined here is helpful.


When to Use undefined in JavaScript

You usually let the language produce undefined for you. Still, understanding when and why it appears helps you design cleaner APIs and fewer surprise bugs.

1. Signaling “Not Provided Yet”

Uninitialized variables and missing parameters are clear examples of “value not provided yet.” For configuration objects or options, you might rely on that behavior:

function setupPlayer(options) {
  if (options.volume === undefined) {
    options.volume = 0.5;
  }
}

Here, checking for undefined distinguishes “no volume given” from “volume set to 0.”

2. Optional Properties and Fields

Some data structures have fields that only make sense in certain cases. For example, a user record might have a phone number, but not always.

const profile = {
  name: "Ravi",
  email: "ravi@example.com",
  phone: undefined // or simply left out
};

Consuming code can treat undefined as “no value stored yet,” which works well with optional chaining and default values.

3. Detecting Bugs and Missing Returns

Seeing JavaScript undefined where you expected a number, string, or object can point straight at a bug. A forgotten return statement stands out once you explicitly test for undefined:

function calculateTotal(price, taxRate) {
  if (price < 0) {
    console.log("Invalid price");
    // Forgot to return here
  }
  return price * (1 + taxRate);
}

If the function returns undefined in some branch, your tests can catch that early.

4. Array Holes and Sparse Data

Arrays sometimes contain “holes” where an index is inside the length but has no value assigned. Those elements show up as undefined:

const scores = [];
scores[3] = 10;

console.log(scores[0]); // undefined
console.log(scores[3]); // 10
console.log(scores.length); // 4

Understanding how undefined behaves in these cases keeps loops and transformations accurate.


Examples of undefined in JavaScript

Let’s look at practical examples that mirror situations you’ll face in real projects.

Example 1: Default Settings Object

Imagine configuring a music player. Users can override defaults, but any missing options fall back to safe values.

function createPlayer(options) {
  const volume = options.volume === undefined ? 0.7 : options.volume;
  const muted = options.muted === undefined ? false : options.muted;

  return { volume, muted };
}

const player = createPlayer({ volume: 0.3 });
console.log(player); // { volume: 0.3, muted: false }

This pattern uses a direct JavaScript check if undefined to distinguish “no value provided” from a valid falsy value like false.

Example 2: Optional Chaining for Nested Data

Consider user data where some people add a social handle, and some don’t:

const user = {
  name: "Marta",
  socials: {
    twitter: "@marta_dev"
  }
};

const instagram = user.socials?.instagram;
console.log(instagram); // undefined

Optional chaining prevents a crash if socials were undefined. Instead, you get undefined, which you can handle gracefully:

const displayInstagram = user.socials?.instagram ?? "No Instagram linked";
console.log(displayInstagram);

Example 3: Handling API Responses

Back-end services often omit fields that are not relevant, instead of sending null. That means you see undefined JavaScript properties in parsed JSON.

const apiResponse = {
  id: 104,
  name: "Chen",
  // subscriptionStatus might be missing
};

function printStatus(user) {
  const status = user.subscriptionStatus ?? "free";
  console.log(`Subscription: ${status}`);
}

printStatus(apiResponse); // "Subscription: free"

This approach reads clearly and plays nicely with undefined and null.

Example 4: Guarding Against Missing Returns

In a function that should always return a number, undefined is a red flag.

function getDiscountPercentage(userType) {
  if (userType === "member") {
    return 0.2;
  }
  if (userType === "student") {
    return 0.15;
  }
  // Forgot a default return here
}

const discount = getDiscountPercentage("guest");

if (discount === undefined) {
  console.log("Unexpected result, missing discount for this user type.");
}

This gives you quick feedback that something is missing.

Example 5: Filtering Out Undefined Values

Sometimes you build an array where some positions are intentionally left undefined, then clean it up.

const rawScores = [10, undefined, 15, undefined, 20];

const validScores = rawScores.filter(score => score !== undefined);
console.log(validScores); // [10, 15, 20]

This approach is common when transforming or normalizing data coming from mixed sources.


Learn More About undefined in JavaScript

Understanding the details around undefined gives you stronger mental models for JavaScript behavior.

JavaScript undefined vs null

Both undefined and null represent “no value,” but they arrive from different paths:

  • undefined usually means “not assigned yet” or “not present.”
  • null usually means “assigned deliberately to represent nothing.”

Some quick comparisons:

console.log(undefined == null);  // true
console.log(undefined === null); // false

Loose equality (==) treats them as equal, while strict equality (===) keeps them separate. Most codebases lean on strict checks for clarity.

How to Check for undefined Safely

Two common patterns appear again and again in tutorials and codebases.

if (value === undefined) {
  // handle missing value
}

This works when you know value has been declared.

To avoid ReferenceError with undeclared variables, you can also use typeof.

if (typeof maybeValue === "undefined") {
  // safe even if maybeValue was never declared
}

Use strict checks when possible, and typeof when you’re not sure a variable exists.

Default Parameters and Destructuring

Default parameters treat undefined in a special way. The default only applies when the argument is undefined, not when it’s another falsy value.

function sendEmail(to, subject = "No subject") {
  console.log(`To: ${to} | Subject: ${subject}`);
}

sendEmail("dev@example.com");            // subject: "No subject"
sendEmail("dev@example.com", null);      // subject: null
sendEmail("dev@example.com", "Welcome"); // subject: "Welcome"

Destructuring behaves the same way:

const settings = { theme: "dark" };

const { theme, language = "en" } = settings;

console.log(theme);    // "dark"
console.log(language); // "en" because settings.language was undefined

Understanding this interaction avoids surprising behavior when you rely on default values.

Truthiness and Pitfalls

undefined is falsy, which means it behaves like false in conditions:

let value;

if (!value) {
  console.log("value is falsy (could be undefined, 0, '', null, etc.)");
}

This pattern is convenient, but sometimes too broad. If you care specifically about undefined and want to distinguish it from 0 or "", stick with explicit checks:

if (value === undefined) {
  console.log("value is specifically undefined");
}

Choosing between a broad falsy check and a precise undefined check depends on your intent.

Optional Chaining and Nullish Coalescing

Modern JavaScript syntax makes it much nicer to work with possibly missing values.

Optional chaining (?.) stops property access if something in the chain is null or undefined:

const city = user.address?.city;

If address is missing, city becomes undefined instead of throwing an error.

Nullish coalescing (??) gives you a default only if the left side is null or undefined:

const timezone = user.settings?.timezone ?? "UTC";

This combination covers many of the situations where you would otherwise write several separate statements.

Style Guidelines and Reassigning undefined

Older code sometimes played tricks like assigning to undefined:

undefined = 5; // please don't do this, even if some engines allow it

Modern best practice: treat undefined as a fixed primitive and never reassign it. Use clear checks and modern syntax instead of clever hacks.

Many teams also avoid assigning undefined on purpose and prefer to leave properties out or use null for explicit emptiness. That choice makes it easier for teammates to read your intent.


Summary

JavaScript undefined represents “no value has been assigned here yet,” and understanding that idea clearly makes debugging far easier. You’ll see undefined in uninitialized variables, missing properties, functions with missing arguments, and branches that forget to return.

Instead of treating it as a weird corner case, you can use it as a signal that something is incomplete or optional.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.