Introduction
In this tutorial, you will learn about JavaScript Null vs Undefined.
Null and undefined represent empty or missing values.
Many Developers get confused between these two, so I will clear each.
What is null in JavaScript?
null is an intentional empty value. If you declare a variable and define the value null in it.
let name = null;
console.log(name); // null
Note: If you declare a null value, that means it does not have any value.
What is undefined in JavaScript?
undefined means a variable has been declared but not assigned any value.
let name;
console.log(name); // undefined
Difference between Null vs Undefined
You can clear the difference through the details below.
| null | undefined |
|---|---|
| It is a Intentional empty value. | Variable not assigned. |
| Type of Null is a object. | Type of Undefined is undefined. |
| Null is declared by Developer. | Undefined is declared by JavaScript. |
| Null means value exists. | Undefined means value not exists. |
Type Checking
Now, you will check Type Checking through below code.
1. typeof null returns Object.
2. typeof undefined returns undefined.
typeof null; // "object"
typeof undefined; // "undefined"
Comparison of null vs undefined
null == undefined // true
null === undefined // false
Note:
== is used to check only the value.
=== is used to check value and type.
Real Life Example: Null vs Undefined in JavaScript
1. Undefined Example (Value Not Assigned Yet)
Suppose, you create a user profile form, but the user has not filled the mobileNumber yet.
let mobileNumber;
console.log(mobileNumber); // undefined
Explanation:
The variable mobileNumber is declared but not assigned a value, so JavaScript automatically sets it to undefined.
2. Null Example (Value Intentionally Empty)
Now suppose the user chooses not to provide a middle name.
Example:
let middleName = null;
console.log(middleName); // null
Explanation:
Here, the developer intentionally assigns null to show that the value does not exist.
Interview Questions
Q 1: What is undefined in JavaScript?
Q 2: What is null in JavaScript?
Q 3: What will this code output console.log(null == undefined);
Because loose equality (==) treats them as equal.Q 4: What will this code output console.log(null === undefined);
Because strict equality (===) checks both type and value.Q 5: When should we use null?
Example:
Reset object
Clear data
No result foundConclusion
Both null and undefined represent that a value does not exist in JavaScript, but they are used in different situations.
Undefined means a variable has been declared but has not been assigned a value yet.
Null means the developer intentionally sets a variable to an empty value.
If developers understand the difference between null and undefined, then they write cleaner code and avoid common bugs in JavaScript applications.