You’ve probably heard to always use === in JavaScript. But there’s one exception even experienced developers use: == null. Let’s understand why.

The Problem with Falsy Values

Imagine a shopping cart system:

const cart = {
  coupon: null, // No coupon applied
  discount: 0,  // 0% discount
  items: []     // Empty cart
};

function showCartSummary(cart) {
  if (!cart.coupon) {
    console.log("No coupon applied"); // Fires for null/undefined
  }
  if (!cart.discount) {
    console.log("No discount"); // Oops! Fires for 0 too
  }
}

The issue? We want to treat null/undefined differently than other falsy values like 0 or empty string.

The == null Solution

== null checks specifically for null or undefined:

function showCartSummary(cart) {
  if (cart.coupon == null) {
    console.log("No coupon applied"); // Only for null/undefined
  }
  if (cart.discount == null) {
    console.log("Discount not set"); // Doesn't trigger for 0
  }
}

Why This Works

In JavaScript, null == undefined returns true, but:

null == 0      // false
null == ""     // false
null == false  // false

Real-World Use Cases

Common patterns where == null shines:

// 1. Default values
function setPrice(price) {
  return price == null ? 10 : price;
}

// 2. Optional function parameters
function createUser(name, email) {
  if (email == null) email = "default@example.com";
}

// 3. Checking API responses
const response = await fetchData();
if (response.error == null) {
  // Proceed safely
}

When Not to Use It

Stick with === for:

// Comparing with 0, false, or empty string
if (count === 0) {...}

// Type-sensitive comparisons
if (typeof value === "string") {...}

Conclusion

== null is:

  • A safe exception to the === rule
  • Perfect for checking null/undefined
  • Not for other falsy values

Used intentionally, it makes your null checks cleaner without sacrificing code safety.

Post a Comment

Your email address will not be published. Required fields are marked *