null vs. undefined
null vs undefined in JavaScript:
null: Represents intentional absence.
undefined: Represents an uninitialized variable.
Key Differences:
Feature | null | undefined |
---|---|---|
Meaning | Intentional absence of any value. | Variable declared but not yet assigned a value. |
Type | object (quirk from early JavaScript) | undefined |
Who sets it? | You, the developer. | JavaScript itself (automatically). |
Usage | To intentionally clear a value. | To indicate missing, uninitialized, or unknown state. |
Example of undefined:
a is declared but not assigned any value. JavaScript automatically assigns undefined.
Example of null:
Here, you deliberately assigned null. It means 'this variable should have no value.'
Comparison:
== allows type coercion. === checks value and type — so they are not strictly equal.
Real-world examples: When clearing an object reference:
When a function doesn't return anything:
Functions without a return implicitly return undefined.