JavaScript  

Difference Between Null and Undefined in JavaScript

🌐 Introduction

In JavaScript, both null and undefined represent the absence of a value. However, they are not the same thing. Many beginners get confused between them, but understanding the difference is essential for writing clean and bug-free code.

❓ What is Undefined?

Undefined. This means that a variable has been declared but has not yet been assigned a value.

Example

  
    let a;
console.log(a); // Output: undefined
  

Here, the variable a exists, but since no value is assigned, JavaScript automatically assigns it the value undefined.

Other cases when you get undefined.

  • Accessing a property that does not exist.

  • A function that does not return anything.

  • Function parameters not passed.

  
    let obj = {};
console.log(obj.name); // undefined (property does not exist)

function test() {}
console.log(test()); // undefined (no return value)

function greet(name) {
  console.log("Hello " + name);
}
greet(); // Hello undefined (parameter not provided)
  

🛑 What is Null?

Null is an assignment value. It represents "nothing" or "empty value." Unlike undefined, you must explicitly assign null to a variable.

Example

  
    let b = null;
console.log(b); // Output: null
  

This means the variable b exists and is assigned a value, but the value is intentionally empty.

🔑 Key Differences Between Null and Undefined

  1. Type

    • undefined is a type itself.

    • Null is an object.

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

    • undefined is automatically assigned by JavaScript when no value is given.

    • The programmer manually assigns null.

  3. Meaning

    • undefined: variable declared but not initialized.

    • Null: intentional empty value.

  4. Comparison

    • null == undefined: true (because both are considered empty).

    • null === undefined: false (because their types are different).

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

📊 When to Use Null vs Undefined

  • Use undefined: Let JavaScript handle it automatically when values are missing.

  • Use null: When you want to intentionally clear a value, e.g., resetting a variable or object property.

Example

  
    let user = {
  name: "John",
  age: 25
};

// User logs out → reset data
user = null;
console.log(user); // null (intentional empty value)

// Declared but not assigned
let data;
console.log(data); // undefined
  

📌 Summary

In JavaScript, both null and undefined represent empty or missing values, but they serve different purposes. Undefined is automatically assigned when a variable is declared without a value, while developers explicitly assign null to represent an intentional empty value. Understanding the difference helps avoid bugs and write cleaner code.