Skip to main content

Building Blocks in JS

Data types in depth - Null and undefined

Coding in JavaScript can be fascinating once you know the gotcha's, the tricky parts in Javascript, one such concept in my opinion is the use of null and undefined especially in the initial stages of learning.

At first glance, they might seem like twins – both representing the absence of a value. But as you dig deeper, you’ll see they are quite different, each with its own role in the world of JavaScript.

Imagine you’re ordering groceries from your favorite app, maybe BigBasket or Grofers. You’ve got your basket filled with rice, spices, and some vegetables. However, when you’re about to check out, you notice that the website says: “Product Unavailable” for one of the items – say the much-coveted Basmati Rice. Now, here’s where things get interesting.

In this scenario:

  • undefined represents the case when the product has not been mentioned at all, or its quantity hasn't been set yet.
  • null represents the case when the product is specifically mentioned as unavailable, meaning there was something expected, but now it’s missing.

Let’s see how this plays out in JavaScript.

undefined: When Something is Uninitialized

In JavaScript, undefined is used to indicate the absence of a value before it has been explicitly assigned. In simpler terms, it’s like adding an item to your grocery list but forgetting to specify its quantity. JavaScript knows the item exists in your list but doesn’t know how much of it you want. It’s uninitialized.

Example 1: Undefined quantity

let groceryList = {
  basmatiRice: undefined, // You haven't specified how much rice you want
  spices: 500, // Quantity is specified
};

In the example above, the basmatiRice item is undefined because you haven't decided on its quantity yet. It’s similar to browsing through BigBasket and adding rice to your cart but not specifying how many kilograms you need.

How undefined works by default

Let’s dig a little deeper into how undefined behaves when you simply declare a variable without assigning a value. This is like creating a grocery list but forgetting to add any items.

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

Here, shoppingItem is declared but not assigned any value, so JavaScript automatically marks it as undefined. It’s like opening an empty shopping cart on an app. The cart exists, but it’s completely unfilled.

Imagine walking into your local kirana (grocery) store and asking the shopkeeper for something you haven’t yet decided upon. The shopkeeper has your basket but doesn’t know what to put inside. This is what undefined feels like in JavaScript – the space for a value exists, but the value itself hasn’t been decided yet, got it?

null: When Something is Intentionally Empty

While undefined is the absence of a value before you assign anything, null is when you intentionally assign "nothing." It’s as if you’ve ordered something, but halfway through the checkout process, you canceled that order. The item is now explicitly marked as unavailable / not required.

let groceryList = {
  basmatiRice: null, // You've explicitly marked this as unavailable
  spices: 500, // Quantity is specified
};

In the above case, basmatiRice is assigned the valuenull, which means you actively decided to cancel this item from your list. It’s different from undefined because here, you’re making a deliberate choice that the rice is not required.

Simply put, just remember that undefined is either the initial state where the value is not assigned or is like an empty basket, but null is like saying, "hey, I need this to be empty", hence assigning the null value to a variable, it is like emptying the basket intentionally. I hope that makes sense!

Let's take one more example:

Think about ordering Alphonso mangoes during the off-season. You added them to your list, but upon checkout, the app informs you that the product is unavailable. You didn’t forget about the mangoes (like undefined), but they simply cannot be delivered at this moment. So, it’s like JavaScript telling you, “This item was once here, but now it’s unavailable.”

Differences Between null and undefined

  • Type Comparison: In JavaScript, null is an object, while undefined is its own type. This difference can trip up beginners but becomes clearer with practice.

Try running this code in your browser console:

console.log(typeof null); // "object"
console.log(typeof undefined); // "undefined"

Intent:undefined is unintentional – it means something hasn’t been initialized yet.null is intentional – it’s a deliberate decision to leave something empty.

  • Usage in Code: You’ll typically encounter undefined when dealing with variables that haven’t been assigned a value or when functions don’t explicitly return anything. On the other hand, you’ll use null when you want to reset a value or indicate that something is missing on purpose.

Using null and undefined in Functions

Let’s take our grocery analogy further. Say you’ve built an online grocery app, and you want to write a function to calculate the total bill. However, some items might not be available (i.e., null), and some might not have a specified quantity yet (i.e., undefined).

function calculateTotal(groceries) {
  let total = 0;

  if (groceries.basmatiRice !== null && groceries.basmatiRice !== undefined) {
    total += groceries.basmatiRice * 80; // Price per kg is ₹80
  }

  if (groceries.spices !== null && groceries.spices !== undefined) {
    total += groceries.spices * 100; // Price per 500g pack is ₹100
  }

  return total;
}

let groceryList = {
  basmatiRice: null,  // Unavailable item
  spices: 2, // 2 packs
};

console.log(calculateTotal(groceryList)); // ₹200 (for 2 packs of spices)

In the example above, we’re checking for both null and undefined to handle cases where an item might be missing or uninitialized.

The Evolution of undefined and null in JavaScript

JavaScript’s null and undefined have an interesting history. Initially, undefined was used internally by JavaScript engines when a variable was declared but not assigned. However, null was introduced as a way for developers to intentionally clear a value. Over time, these two values became integral to handling missing or unknown data.

Fun Fact:

You might find this surprising, but in JavaScript:

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

The loose equality (==) considers null and undefined to be equal because they both represent “no value.” But strict equality (===) checks for both value and type, revealing their differences.

We have learned about this in one of the previous articles on equality operators, I would suggest reading the article again to ensure you understand this concept very well.

Common Mistakes with null and undefined

Let’s face it – even seasoned developers can mix up null and undefined. Even I have committed these mistakes early in my career. Here are some common pitfalls and how to avoid them:

1. Forgetting to Check for undefined

This often happens when you assume a variable has a value. For instance, in our online grocery app, if you forget to check forundefined, the function might try to perform calculations with a missing value.

function calculatePrice(item) {
  return item.quantity * item.price;
}

let apple = { quantity: undefined, price: 30 };
console.log(calculatePrice(apple)); // NaN (because undefined * 30 is not a number)

Solution:

Always check if a value is undefined before performing operations on it.

function calculatePrice(item) {
  if (item.quantity !== undefined && item.price !== undefined) {
    return item.quantity * item.price;
  }
  return 0;
}

2. Assigning undefined Directly

While you can assign null to reset a variable, assigning undefined directly is generally discouraged. It’s better to let JavaScript handle undefined automatically.

let product = null; // Good practice
let product = undefined; // Not recommended

When to use null and undefined

In everyday coding, you’ll come across situations where you need to choose between null and undefined. Here’s a simple guide:

  • Use undefined for variables that haven’t been initialized or when a function doesn’t return a value.
  • Use null when you want to explicitly clear or indicate the absence of a value.

In JavaScript, null and undefined serve different purposes in representing “nothingness.” Whether you're building an online grocery app or handling complex data, understanding when to use these values can save you from bugs.

Shrikanth's pro tip: Ensure to run the code I share in the articles in your browser console or in your preferred environment, learning by doing is the best way to master it!