What is the difference between a JavaScript variable that is: null, undefined or undeclared?

Answer

In JavaScript, null, undefined, and undeclared variables represent different concepts of "no value" or "missing value." Understanding their differences is crucial to avoiding errors and writing cleaner code.

  1. null

Example:

let a = null; // a is explicitly set to "no value"
console.log(a); // null
console.log(typeof a); // "object"
  1. undefined

Example:

let b; // b is declared but not initialized
console.log(b); // undefined
console.log(typeof b); // "undefined"

let obj = {};
console.log(obj.value); // undefined (property does not exist)

function noReturn() {}
console.log(noReturn()); // undefined
  1. Undeclared
console.log(c); // ReferenceError: c is not defined

Note: If you accidentally assign a value to an undeclared variable (without strict mode), JavaScript creates it as a global variable.

Skopiuj kod
"use strict";
x = 5; // ReferenceError: x is not defined

Key Notes

console.log(null == undefined); // true (type coercion)
console.log(null === undefined); // false (strict check)

MDN Web Docs: null

MDN Web Docs: undefined