Undefined Variable
Quick summary
The variable exists but has no value — it is `undefined`, and using it as if it has one causes problems.
Why this happens
Used a variable before assigning a value to it
Variable was declared but never initialized
A function returned
undefinedand the caller used the result directly
Minimal example
let x;
console.log(x.length);let x = "";
console.log(x.length);x is declared but never assigned, so it is undefined — accessing .length on undefined throws a TypeError.
How to diagnose
Log the variable value right before the line that fails
Trace where the variable should have been assigned
Check if a function or API call returned
undefined
How to fix
Assign a value to the variable before using it
Provide a default value (e.g.,
const name = input || 'guest')Add a guard check before using the variable
How to prevent
Initialize variables at the point of declaration
Use default values when reading from APIs or user input
Related Resources
Related Practice
- Variable Declaration Quiz
Test your understanding of variable declaration.
- Declare a Constant Practice
Practice declaring variables.