ResourcesJavascriptGuides

Null vs undefined

Introduction

In JavaScript, null and undefined are two different primitive types representing the absence of value. While they may seem similar, they have different uses and behaviors. In this article I will explain what's the difference. All Javascript data types


Null and undefined

Undefined

undefined is a primitive value automatically assigned to variables that have been declared but not initialized.

let a;
console.log(a); // undefined
 
function foo() {}
let result = foo();
console.log(result); // undefined

When is undefined used?

  • Variable declared but not assigned a value.
  • Function is called but doesn't return a value.
  • Property does not exist in an object.
  • Accessing array elements outside the array bounds.

Null

null is a primitive value that represents the intentional absence of any object value. It is explicitly assigned by the programmer to indicate "no value."

let b = null;
console.log(b); // null
 
let person = { name: "Alice", age: null };
console.log(person.age); // null

When is null used?

  • Intentionally setting a variable to have no value.
  • Resetting or clearing a variable to indicate no value.

Key difference between null and undefined

1. Type

  • undefined is type undefined
  • null is type object
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"

2. Usage

  • undefined is used by JavaScript in various cases as a default value
  • null is used by programmers to intentionally denote the absence of a value

3. Equality

  • == (loose equality): null and undefined are equal.
  • === (strict equality): null and undefined are not equal.

More examples

Unassigned parameters are undefined

function greet(name) {
  console.log(name); // undefined if no argument is passed
}
greet(); // no argument while calling greet function

Object properties

let car = { brand: "BMW" };
console.log(car.model); // undefined
console.log(car.brand) // BMW

Intentionally setting value to null

let data = { name: "Pawel" };
data.name = null;
 
console.log(data.name); // nulls

Resources

MDN Web docs - null MDN Web docs - undefined

On this page