TypeError: Cannot set properties of undefined
TypeError: Cannot set properties of undefined in JavaScript means you tried to set a property on a variable or object that is undefined or null (e.g. user.profile.name = 'Ada' when user.profile does not exist).
How do I fix TypeError: Cannot set properties of undefined?
To fix TypeError: Cannot set properties of undefined in JavaScript, locate the line causing the error and check the values right before it runs. Most occurrences happen because of assigning to a nested property on an empty object. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does TypeError: Cannot set properties of undefined mean?
JavaScript cannot attach a new property to a primitive undefined or null value. The error message usually specifies which property you attempted to set. The actual problem is that the parent container was never initialized.
Why does TypeError: Cannot set properties of undefined happen?
1. Assigning to a nested property on an empty object
The parent object user.profile is undefined, so assigning .name throws.
Breaks
const user = {};
user.profile.name = "Ada";Works
const user = { profile: {} };
user.profile.name = "Ada";2. Building a 2D matrix without initializing rows
grid[i] is undefined, so grid[i][j] cannot be assigned.
Breaks
const grid = [];
grid[0][0] = "X";Works
const grid = [];
grid[0] = [];
grid[0][0] = "X";3. State or ref has not mounted yet
Accessing ref.current.style before the DOM element renders throws because ref.current is undefined.
Breaks
inputRef.current.value = "reset";Works
if (inputRef.current) {
inputRef.current.value = "reset";
}How to find it in your own code
Ensure all parent objects are initialized before assigning nested properties: `user.profile = user.profile || {}; user.profile.name = 'Ada';` or check the parent exists before assignment.
Try it: fix this bug
easygetUserCity({}) throws TypeError: Cannot read properties of undefined (reading 'city').
function getUserCity(user) {
return user.address.city;
}More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser โ no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.