null vs. undefined

null vs undefined in JavaScript:

null: Represents intentional absence.

undefined: Represents an uninitialized variable.

Key Differences:

Featurenullundefined
MeaningIntentional absence of any value.Variable declared but not yet assigned a value.
Typeobject (quirk from early JavaScript)undefined
Who sets it?You, the developer.JavaScript itself (automatically).
UsageTo intentionally clear a value.To indicate missing, uninitialized, or unknown state.

Example of undefined:

javascript
1let a; 2console.log(a); // Output: undefined

a is declared but not assigned any value. JavaScript automatically assigns undefined.

Example of null:

javascript
1let b = null; 2console.log(b); // Output: null

Here, you deliberately assigned null. It means 'this variable should have no value.'

Comparison:

javascript
1console.log(null == undefined); // true (loose equality - values are considered equal) 2console.log(null === undefined); // false (strict equality - types are different)

== allows type coercion. === checks value and type — so they are not strictly equal.

Real-world examples: When clearing an object reference:

javascript
1let user = { name: "Alice" }; 2user = null; // Done working with user

When a function doesn't return anything:

javascript
1function sayHello() { 2 console.log("Hello"); 3} 4 5const result = sayHello(); 6console.log(result); // Output: undefined

Functions without a return implicitly return undefined.