Chapter 12

JavaScript null and undefined

null and undefined can both represent missing or unavailable values, but they have different meanings.

What is JavaScript null and undefined?

  • undefined commonly means that a value has not been assigned.
  • null can be used intentionally to represent an empty or absent value.
  • Both values should be handled carefully in application logic.
  • The typeof operator returns 'undefined' for an undefined value.

Syntax

let value;
let selectedCourse = null;

console.log(value);
console.log(selectedCourse);

Example

Try understanding this code before running it.
let studentName;
let selectedCourse = null;

console.log(studentName);
console.log(selectedCourse);

if (studentName === undefined) {
    console.log('Name is not assigned');
}

Important Points

  • undefined and null are semantically different.
  • Strict comparison such as === is useful for clear checks.
  • Missing API data and optional values may need null or undefined checks.

Common Mistakes

  • Assuming null and undefined are always identical.
  • Calling a method on a value without checking whether it exists.
  • Relying on loose equality without understanding its behavior.

Real-World Use

Database fields, API responses, optional form fields, and application state can contain null or undefined values.

Practice Exercise

Practice: null and undefined
Create one undefined variable and one null variable. Display both values and their typeof results.

Ready to write code?

Open the JavaScript editor and run your code with live output.

Try It Yourself →