Skip to main content

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:

  1. If a variable is declared but not initialized:
javascript
let user; console.log(user); // undefined
  1. If a function returns nothing:
javascript
function greet() {} console.log(greet()); // undefined
  1. If you access a non-existent object property:
javascript
const obj = {}; console.log(obj.age); // undefined

undefined is 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:

  1. When you want to explicitly show that a value is absent:
javascript
let user = null; // no user yet
  1. When you need to clear a variable:
javascript
user = null; // remove the reference to the object
  1. 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

null is a deliberate "nothing", while undefined is an accidental "nothing".


Comparing null and undefined

Propertyundefinednull
Type (typeof)"undefined""object" (a spec bug that stuck around historically)
Assigned automaticallyYesNo
Assigned manuallyRarelyOften
Default valueFor uninitialized variablesNo
Used for "value is absent"NoYes
Used for "value is not set"YesNo

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 undefined for:
    • uninitialized variables;
    • missing function arguments;
    • checks for "is there a value" (if (value === undefined)).
  • Use null for:
    • 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 user

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.