DEV Community

Cover image for What is the difference between Null and undefined in JavaScript?
Tanvir Ahmed
Tanvir Ahmed

Posted on • Edited on

What is the difference between Null and undefined in JavaScript?

Null

In JavaScript, null is a primitive value that represents the intentional absence of any object value. It is one of JavaScript's falsy values, meaning it evaluates to false in boolean contexts. However, it is distinct from undefined, which represents a variable that has been declared but has not been assigned a value.

  • null is a special primitive value, but when you check its type using typeof, it returns "object".

Image description
null is used when a variable is expected to hold an object but currently doesn't have one. It signals the intentional absence of a value.

let person = null;  // The `person` variable explicitly has no value.
Enter fullscreen mode Exit fullscreen mode

Used when you intentionally want to signify "no value" or "empty."


Undefined

In JavaScript, undefined is a primitive value automatically assigned to variables that have been declared but not yet assigned a value.

  • undefined is a primitive type in JavaScript. It refers to variables that have been declared but not initialized, and its typeof will correctly reflect "undefined".
let x;
console.log(typeof x);         // "undefined"
Enter fullscreen mode Exit fullscreen mode

Difference Between null and undefined

Image description
In this example, uninitializedVariable is undefined because it hasn't been assigned any value.
Meanwhile, objectWithNoValue is explicitly set to null, signaling that it should hold an object, but currently it doesn’t.

Comparison

  • Loose equality (==) null and undefined are loosely equal because they both represent an "empty" value.
console.log(null == undefined);  // true
Enter fullscreen mode Exit fullscreen mode
  • Strict equality (===) They are not strictly equal because they are different types.
console.log(null == undefined);  // true
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more