Undefined versus null in JavaScript

David Y.

The Problem

What is the difference between the values undefined and null in JavaScript?

The Solution

When a variable has been declared but not yet assigned a value, it will have the type and value undefined. undefined is one of JavaScript’s primitive types.

let myVar; console.log(myVar); // will print "undefined" console.log(typeof myVar); // will also print "undefined"

When a variable has not been declared or assigned, it will also be of type undefined and throw a ReferenceError when accessed. Therefore, typeof will produce the same result for declared but undefined variables and undeclared variables.

console.log(undeclaredVar); // will throw a ReferenceError console.log(typeof undeclaredVar); // will print "undefined"

In contrast, null is a value that represents nothing. Think of null as an empty container and undefined as the absence of a container. A variable will only have the value null when it is explicitly assigned, and will be of type object.

const myVar = null; console.log(myVar); // will print "null" console.log(typeof myVar); // will print "object"

The difference between undefined and null is important when using JavaScript’s equality operators. null and undefined are considered the same when using loose equality (==) but not when using strict equality (===).

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

Get Started With Sentry

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a JavaScript project and note your DSN

  3. Grab the Sentry JavaScript SDK

<script src="https://browser.sentry-cdn.com/7.110.1/bundle.min.js"></script>
  1. Configure your DSN
Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.