Sentry Answers>JavaScript>

Undefined versus null in JavaScript

Undefined versus null in JavaScript

David Y.

The ProblemJump To Solution

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.

Click to Copy
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.

Click to Copy
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.

Click to Copy
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 (===).

Click to Copy
console.log(undefined == null); // will print "true" console.log(undefined === null); // will print "false"
  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

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.

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