Differences between Null and Undefined in JavaScript

In JavaScript, “null” and “undefined” are two special values that often confuse developers due to their similar use cases.

However, they have distinct meanings and use cases. In this detailed article, we’ll explore the differences between null and undefined to help you understand when and how to use each one.

Introduction

In JavaScript, both “null” and “undefinedrepresent the absence of a value, but they are used in different contexts. Understanding their distinctions is crucial for writing robust and error-free code.

Table of Contents #
  1. null in JavaScript
  2. undefined in JavaScript
  3. When to Use null
  4. When to Use undefined
  5. Common Pitfalls and Best Practices
  6. Comparison and Type Equality
  7. Examples of Undefined
  8. Null Examples
  9. Null and undefined comparison table
  10. Why is null an object
  11. Conclusion

1. “NULL” in JavaScript

Null as an Assigned Value

null is a primitive value in JavaScript that represents the intentional absence of any object value. It is often assigned to variables or properties to signify the absence of a meaningful value.

let myVariable = null;

Checking for Null

To check if a value is “null”, you can use a strict equality check (===) because null is of type object.

if (myVariable === null) {
    console.log('The variable is null.');
} else {
    console.log('The variable is not null.');
}

2. “Undefined” in JavaScript

Undefined as the Absence of Value

undefined in JavaScript represents the absence of a defined value. It is often the default value of variables that have been declared but not assigned a value.

let anotherVariable;
console.log(anotherVariable); // Outputs: undefined

Checking for Undefined

To check if a value is undefined, you can use both loose equality (==) and strict equality (===) because undefined is not limited to a specific type.

if (typeof anotherVariable === 'undefined') {
    console.log('The variable is undefined.');
} else {
    console.log('The variable is defined.');
}

3. When to Use null

  • Explicit Absence of Value: Use null when you want to explicitly indicate that a variable or property has no meaningful value.
  • Resetting Values: It can be used to reset the value of a variable or property.

4. When to Use undefined

  • Default Value: JavaScript assigns undefined as the default value to variables and function parameters that have been declared but not assigned a value.
  • Checking for Presence: When checking if a variable has been defined or initialized.

5. Common Pitfalls and Best Practices

  • Avoid Reassigning undefined: It’s generally not advisable to manually assign undefined to a variable. Let JavaScript handle the default assignment.
  • Use Strict Equality: When checking for equality, prefer using strict equality (===) to avoid type coercion.

6. Comparison and Type Equality

null == undefined; // true
null === undefined; // false

In loose equality (==), null and undefined are considered equal. However, in strict equality (===), they are of different types and, therefore, not equal.

7. Examples of Undefined

  • Variable is declared but not assigned a value

    When a variable is declared but not assigned a value, it is automatically (implicitly) initialized with undefined.

    let name; // Variable is Declared But Not Assigned a Value
    console.log(name); // Output: undefined
    
    name = "John"; // Assigning a Value (John) to the name Variable
    console.log(name); // Output: John
  • When a function returns nothing

    If a function does not have a return statement, it will return undefined by default.

    function sayHi() {
        console.log("HI");
    }
    
    const data = sayHi();
    console.log(data); // Output: undefined
  • Access a property that doesn’t exist in an object

    When you access a property that doesn’t exist in an object, JavaScript will return undefined to indicate that the property is not present or hasn’t been assigned a value.

    const user = {
        name: "John",
        age: 23,
        email: "dd",
    };
    
    console.log(user.email); // Output: undefined
    
    /**
     * Use `in` operator or hasOwnProperty() to check
     * whether property is exist
     */
    if ("email" in user) {
        console.log(user.email);
    }
  • Best Practice

    An explicit assignment of undefined is possible but generally not recommended, as it can be misleading and it is better to rely on JavaScript’s default behavior for uninitialized variables.

    let user1 = undefined; // ❌
    let user2 = null; // ✔️ use `null` instead.

8. Null Examples

  • Null needs to be assigned explicitly

    null is a value that needs to be assigned explicitly to indicate the intentional absence of a value or emptiness.

    let user = null; // Empty variable
  • JavaScript implicitly converts null to 0

    JavaScript implicitly converts null to 0 when performing arithmetic operations.

    console.log(null + 2); // 2 because 0 + 2 = 2
    console.log(null * 5); // 0 because 0 * 5 = 0

9. Null and undefined comparison table

NullUndefined
You can put null in a variable to say there’s nothing here.Undefined means a variable has been declared but no value has been assigned yet.
null is a primitive type of value in JS.undefined itself is a type as well as a value.
JS converts null to 0 when performing arithmetic operations.When performing arithmetic operations it returns NaN – which means ‘not a number’.

10. Why is null an object?

“null” is a primitive type of value, but when you check its type using typeof you will get object.

console.log(typeof null); // Output: object

Many people consider this behavior a bug. Changing or fixing this bug may break a lot of existing code that relied on this behavior, so it has not been changed yet. But this is a theory.

There is another popular theory behind this. In the early versions of JavaScript, the first 3 bits of a value stored in 32 bits represented the data type and the remaining bits represented the value.

At that time the first 3 bits of all object type values started with 000. Null usually means empty, so it had all 0’s stored in 32 bits. JavaScript sees the starting 3 zeros in null, thinks it’s an object, and goes with it.

first 3 bits of all object type values started with 000

This mistake has persisted over time due to the need to maintain backward compatibility with existing code.

Conclusion

Understanding the difference between “null” and “undefined” is fundamental for writing clean and bug-free JavaScript code.

While they both represent the absence of a value, they are used in distinct scenarios. Proper usage of null and undefined contributes to code clarity and helps avoid common pitfalls associated with their misuse.

By following best practices and understanding their behavior, you can write more robust and maintainable JavaScript applications.