What is the difference between null and undefined?
undefined
What it is: The value "undefined" (not defined). Means the variable exists, but holds nothing.
When it appears:
- If a variable is declared but not initialized:
javascript
let user;
console.log(user); // undefined- If a function returns nothing:
javascript
function greet() {}
console.log(greet()); // undefined- If you access a non-existent object property:
javascript
const obj = {};
console.log(obj.age); // undefined
undefinedis usually created automatically by the JS engine, not manually.
null
What it is: The value "empty" or "nothing here", which the developer assigns explicitly.
When to use it:
- When you want to explicitly show that a value is absent:
javascript
let user = null; // no user yet- When you need to clear a variable:
javascript
user = null; // remove the reference to the object- When working with a DB or API, where a field's value can be "empty":
javascript
user.email = null; // the user did not provide an email
nullis a deliberate "nothing", whileundefinedis an accidental "nothing".
Comparing null and undefined
| Property | undefined | null |
|---|---|---|
Type (typeof) | "undefined" | "object" (a spec bug that stuck around historically) |
| Assigned automatically | Yes | No |
| Assigned manually | Rarely | Often |
| Default value | For uninitialized variables | No |
| Used for "value is absent" | No | Yes |
| Used for "value is not set" | Yes | No |
How to compare them
javascript
null == undefined // true → loose comparison (they are equal by value)
null === undefined // false → strict comparison (different types)Usage recommendations
- Use
undefinedfor:- uninitialized variables;
- missing function arguments;
- checks for "is there a value" (
if (value === undefined)).
- Use
nullfor:- deliberately clearing a value;
- indicating "value is absent" in program logic or an API;
- compatibility with JSON and databases.
Example:
javascript
let user; // undefined - the variable is declared, but empty
user = null; // null - explicitly stated that there is no userShort Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.