What’s the difference between typescript null and undefined?

Jomar M. blog author

Jomar M

Today I learned about the distinction between null and undefined in TypeScript—two terms that often confuse developers but serve different purposes.

Key Points:

  1. null: Represents the intentional absence of any value. Use it when you want to specify that a variable has no value on purpose.

  2. undefined: Indicates that a variable hasn’t been assigned a value yet. It’s the default state for uninitialized variables.

Why It Matters:

• Using null helps to clearly communicate intentional absence, making your code easier to understand.

• Leveraging undefined for uninitialized values is useful when you expect the variable to be assigned later.

This distinction avoids unnecessary bugs and keeps the codebase predictable.

Example of null

let user = null; // Intentional absence of a value console.log(user); // Output: null

Example of undefined

let user; // Variable declared but not initialized console.log(user); // Output: undefined

Checking for both

function checkValue(value: any): void { if (value === null) { console.log("Value is null: Intentionally absent"); } else if (value === undefined) { console.log("Value is undefined: Not yet initialized"); } else { console.log("Value exists:", value); } } checkValue(null); // "Value is null: Intentionally absent" checkValue(undefined); // "Value is undefined: Not yet initialized" checkValue("Jomar"); // "Value exists: Jomar"

Let’s Build Something Great Together!

Ready to make your online presence shine? I’d love to chat about your project and how we can bring your ideas to life.