Skip to content

What is the difference between null and undefined in JavaScript?

THE AHA STACK MASTERCLASS

Now open with 50% off launch discount!

Let’s talk about the similarities first.

null and undefined are JavaScript primitive types.

The meaning of undefined is to say that a variable has declared, but it has no value assigned.

let age //age is undefined
let age = null //age is null

Note: accessing a variable that’s not been declared will raise a ReferenceError: <variable> is not defined error, but this does not mean it’s undefined.

How do you check if a variable is null? Use the comparison operator, for example age === null

Same for undefined: age === undefined

In both cases, you can check for:

if (!age) {

}

and this will be matching both null and undefined.

You can also use the typeof operator:

let age
typeof age //'undefined'

although null is evaluated as an object, even though it is a primitive type:

let age = null
typeof age //'object'

→ Get my JavaScript Beginner's Handbook

I wrote 20 books to help you become a better developer:

  • Astro Handbook
  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • CSS Handbook
  • Node.js Handbook
...download them all now!

Related posts that talk about js: