JavaScript null
What is null?
In JavaScript, null means:
- Intentional absence of any value.
- It is a primitive value that represents "nothing" or "empty"
Developers assign null when they want to say that a variable should have no value.
How to Use null
You assign null manually:
let user = null;
console.log(user); // Output: null
null is explicitly set by the programmer to indicate "no value".
Examples and Outputs
Example 1: Setting null
let car = null;
console.log(car); // Output: null
Example 2: Before and After Assignment
let city = null;
console.log(city); // Output: null
city =
"Paris";
console.log(city); // Output: Paris
Here:
- Initially, city has no value (null).
- Later, a value is assigned.
Type of null
Interestingly, typeof null returns "object" (this is a historical bug in JavaScript that was never fixed).
Example:
let x = null;
console.log(typeof x); // Output: "object"
Even though typeof null is "object" , null is NOT an object — it's a primitive value.
Difference Between undefined and null
Feature | undefined | null |
---|---|---|
Meaning | Variable declared but not assigned | Intentional absence of any value |
Type | "undefined" | "object" |
Set by | JavaScript engine | Developer manually |
Typical Usage | Uninitialized variable | To reset or empty a variable |
Example Comparison
let a;
let b = null;
console.log(a); // Output: undefined
console.log(b); // Output: null
console.log(typeof a); // Output: "undefined"
console.log(typeof b); // Output: "object"
Null in Conditional Statements
In conditions, null behaves like false (it’s falsy).
Example:
let user = null;
if (user) {
console.log("User exists");
} else {
console.log("No user");
}
// Output: No user
null is treated as false in logical expressions.
Checking for null
You can check if a variable is null:
let data = null;
if (data === null) {
console.log("Data is null");
}
// Output: Data is null
Use === (strict equality) to properly check for null without type conversion.