Intern / FresherJavaScript

What is the difference between null and undefined in JavaScript?

Quick answer

undefined means a variable has been declared but no value was assigned; null is an explicit value meaning 'no value' that you assign on purpose.

JavaScript uses undefined automatically: for uninitialised variables, missing function arguments, missing object properties and functions with no return statement. null is something a developer sets deliberately to say that a value is intentionally empty.

typeof undefined is 'undefined', while typeof null is 'object', a long-standing bug in the language that cannot be fixed without breaking the web. Use value == null to test for both, or optional chaining and nullish coalescing (user?.name ?? 'Guest') to handle them safely.

let a;                    // undefined
const b = null;           // null
typeof a;                 // "undefined"
typeof b;                 // "object" (historical bug)
a == b;                   // true
a === b;                  // false
const name = user?.name ?? "Guest";