JavaScript Interview Question #13
What is null, and how is it different from undefined?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
undefined usually represents a value that has not been assigned or is missing, while null is normally used intentionally to represent the absence of a value.
Detailed Explanation
undefined usually represents a value that has not been assigned or is missing, while null is normally used intentionally to represent the absence of a value.
For example, a declared variable without an assigned value is undefined. A developer might explicitly assign null when a value has been checked and intentionally cleared. Although null == undefined is true because of loose equality rules, null === undefined is false because they are different types.
Code Example
let firstName;
const selectedUser = null;
console.log(firstName); // undefined
console.log(selectedUser); // null
console.log(null == undefined); // true
console.log(null === undefined); // false