๐Ÿง  Understanding null vs undefined in JavaScript: From Basics to Interview Mastery

krishankrishan
3 min read

In JavaScript, both null and undefined represent the absence of a value, but they serve different purposes and behave differently. This guide will help you understand these differences, when to use each, and how to tackle related interview questions.


๐ŸŸข Step 1: Beginner โ€” What Are null and undefined?

  • undefined: A variable that has been declared but not assigned a value.

      let a;
      console.log(a); // Output: undefined
    
  • null: An assignment value that represents no value or object. It's intentionally set by the programmer.

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

๐ŸŸก Step 2: Intermediate โ€” When to Use Each

  • Use undefined:

    • When a variable is declared but not initialized.

    • When a function does not return a value explicitly.

    function greet() {}
    console.log(greet()); // Output: undefined
  • Use null:

    • To explicitly indicate that a variable should be empty.

    • To reset or clear a variable's value.

    let user = { name: "Alice" };
    user = null; // User data cleared

๐Ÿ”ด Step 3: Advanced โ€” Key Differences and Behaviors

Featureundefinednull
Typeundefinedobject (historical bug)
Assigned byJavaScript engineDeveloper
Equality (==)null == undefined โ†’ true
Strict Equality (===)null === undefined โ†’ false
Arithmetic Operationsundefined + 1 โ†’ NaNnull + 1 โ†’ 1

๐ŸŽฏ Step 4: Best Practices

  • Avoid assigning undefined manually: Let JavaScript handle it.

  • Use null:

    • To indicate intentional absence of value.

    • When interacting with APIs that return null.

  • Checking for both:

      if (value == null) {
        // Handles both null and undefined
      }
    
  • Use optional chaining and nullish coalescing:

      const name = user?.name ?? "Guest";
    

๐Ÿ’ผ Interview Questions (With Answers)

Q1: What is the difference between null and undefined?

A: undefined means a variable has been declared but not assigned a value. null is an assignment value that represents no value.

Q2: What is the result of typeof null?

A: 'object'. This is a known bug in JavaScript.

Q3: How do null and undefined behave in arithmetic operations?

A: undefined results in NaN; null is coerced to 0.

let x = null;
let y = undefined;

console.log(x + 1); // 1
console.log(y + 1); // NaN

Q4: How would you differentiate between undefined and not defined?

A: undefined is a value; not defined is a ReferenceError when a variable hasnโ€™t been declared.

Q5: Is typeof undefined the same as typeof null?

A: No. typeof undefined is "undefined"; typeof null is "object".

Q6: How does JavaScript treat null and undefined in JSON?

A: undefined values are removed; null is preserved.

JSON.stringify({ a: undefined, b: null });
// Output: {"b":null}

โš›๏ธ React-Specific Examples

1. Conditionally rendering elements with null

const Welcome = ({ user }) => {
  return (
    <div>
      {user ? <h1>Hello, {user.name}</h1> : null}
    </div>
  );
};

2. Optional props and default values

function Profile({ age }) {
  return <p>Age: {age ?? "Not provided"}</p>;
}

3. Initializing state with null

const [selectedUser, setSelectedUser] = useState(null);

useEffect(() => {
  fetchUser().then(user => setSelectedUser(user));
}, []);

4. Avoiding errors with optional chaining

const name = user?.profile?.name ?? "Anonymous";

5. Skipping rendering when data is not ready

if (data === null) {
  return <Spinner />;
}
return <Dashboard data={data} />;

๐Ÿ“š Further Reading

10
Subscribe to my newsletter

Read articles from krishan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

krishan
krishan

๐Ÿ‘‹ Hey, I'm a Frontend Developer passionate about building clean, user-friendly interfaces. ๐Ÿš€ Learning and sharing everything from React, JavaScript, HTML/CSS to advanced topics like Data Structures, Algorithms & System Design. ๐Ÿ’ป Documenting my journey from fundamentals to becoming a top-tier developer โ€” one blog at a time. ๐Ÿ“š Join me as I break down complex topics into easy, practical lessons โ€” with GitHub repos, code snippets, and real-world examples. ๐Ÿ” Consistent growth, community learning, and aiming high!