日本語

How to Fix “Cannot set properties of undefined” Errors in JavaScript

​​JavaScript​Troubleshooting

When you try to put a value into an object that holds settings, or into an object you built by regrouping an array by ID, the browser console may show Uncaught TypeError: Cannot set properties of undefined (setting 'color'). The cause is that a.b in a.b.color = ... does not exist yet, so you are trying to set a property on undefined. If you create the container object first, the error goes away.

I reproduced this error in a test environment and included the messages the console received, as they were. I also confirmed that with the corrected code the error no longer appears and the value is set.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153 (headless) launched with Playwright 1.63.0. I did not open the DevTools window. Instead, I received what the console sent through the DevTools Protocol and displayed it. In every example, the JavaScript file is loaded with <script src> inside the <body> of an HTML page. I did not test Firefox or Safari.

Setting a value inside an object that does not exist yet

The following bad.js creates an empty object settings and then tries to set color inside theme to "blue".

js
const settings = {};
settings.theme.color = "blue";
console.log("色を設定しました:", settings.theme.color);

When I opened a page that loads this bad.js in Chromium, the console received the following (I removed the exception: and similar prefixes that my test script added to each line).

text
Uncaught TypeError: Cannot set properties of undefined (setting 'color')
    at http://127.0.0.1:8125/bad.js:2:22

127.0.0.1:8125 is an HTTP server I ran locally for the test.

The message means "cannot set properties of undefined (I tried to set color)." The 'color' in parentheses is the name of the property you tried to set. What was undefined was settings.theme, the expression just before it, so when you look for the cause, check one step to the left.

The bad.js:2:22 on the second line of the error points to column 22 of line 2 of bad.js, which is the = in settings.theme.color = "blue". Because execution stopped at the error, the console.log on line 3 was never run.

The middle of the left side is undefined

settings is an empty object, so it has no theme property. Reading a property that does not exist does not throw an error; it returns undefined. I printed settings.theme with console.log to check this.

js
const settings = {};
console.log("settings.theme の中身:", String(settings.theme));

The result was as follows.

text
settings.theme の中身: undefined

settings.theme.color = "blue" works in this order: it reads settings.theme, then sets color on the result. The first step returns undefined, and undefined cannot have properties, so a TypeError is thrown. As MDN's explanation of TypeErrors caused by an unexpected type describes, this kind of TypeError happens when you operate on a value that is not the type you expected, often undefined or null.

In JavaScript, writing a.b.c = 1 does not create a.b automatically. You have to create the container object yourself before setting values in it.

Create the container object first

The simplest approach is to assign the whole theme as an object.

js
const settings = {};
settings.theme = { color: "blue" };
console.log("色を設定しました:", settings.theme.color);

If settings.theme may already have other properties (such as fontSize) and you do not want to replace it entirely, use the nullish coalescing assignment operator ??=. It assigns the right-hand value only when the left-hand side is null or undefined.

js
const settings = {};
settings.theme ??= {};
settings.theme.color = "blue";
console.log("色を設定しました:", settings.theme.color);

Neither version raised an error, and the console printed the following.

text
色を設定しました: blue

Setting a value past the end of an array

The same error occurs when you set a value on an object inside an array. The rows array below has only two items, so rows[2] (the third item) is undefined.

js
const rows = [{ name: "りんご" }, { name: "みかん" }];
rows[2].name = "ぶどう";
text
Uncaught TypeError: Cannot set properties of undefined (setting 'name')
    at http://127.0.0.1:8125/array.js:2:14

If you want to add a third item, add the whole object with push.

js
const rows = [{ name: "りんご" }, { name: "みかん" }];
rows.push({ name: "ぶどう" });
console.log("件数:", rows.length, "3件目:", rows[2].name);
text
件数: 3 3件目: ぶどう

If you meant to change an existing row, check that the index is not off by one (for example, that you did not write rows[1] for the first item). Array indexes start at 0.

Grouping an array into objects keyed by ID or name

The same error occurs when you regroup an array into an object that you look up by ID. The following code stopped on the first iteration of the loop.

js
const users = [
  { id: "u1", name: "さくら" },
  { id: "u2", name: "こはる" },
];
const usersById = {};
for (const user of users) {
  usersById[user.id].name = user.name;
}
text
Uncaught TypeError: Cannot set properties of undefined (setting 'name')
    at http://127.0.0.1:8125/byid.js:7:27

usersById is empty, so usersById["u1"] is still undefined. Create the per-ID object in the line where you assign the value.

js
for (const user of users) {
  usersById[user.id] = { name: user.name };
}
console.log("変換した結果:", JSON.stringify(usersById));
text
変換した結果: {"u1":{"name":"さくら"},"u2":{"name":"こはる"}}

Accumulating with += gives a reading error

The same mistake produces a different message when you accumulate with +=. The following code tries to add up the order counts for each item.

js
const orders = [
  { item: "りんご", count: 2 },
  { item: "みかん", count: 1 },
  { item: "りんご", count: 3 },
];
const summary = {};
for (const order of orders) {
  summary[order.item].count += order.count;
}
text
Uncaught TypeError: Cannot read properties of undefined (reading 'count')
    at http://127.0.0.1:8125/group.js:8:10

x += y is the same as x = x + y. It reads the current value, adds to it, and assigns the result back. So execution stops at the read that happens before the assignment, and the message says reading instead of setting. The cause is the same: summary["りんご"] does not exist yet. To create the container only when an item first appears, add one line with ??=.

js
for (const order of orders) {
  summary[order.item] ??= { count: 0 };
  summary[order.item].count += order.count;
}
console.log("集計:", JSON.stringify(summary));
text
集計: {"りんご":{"count":5},"みかん":{"count":1}}

The two orders for apples (りんご) were added together, giving 5.

Calling a class method after extracting it

This error also occurs when you assign to this, as in this.count = 0. The following code extracts the reset method of the Counter class with destructuring and then calls it.

js
class Counter {
  count = 5;
  reset() {
    this.count = 0;
  }
}
const counter = new Counter();
const { reset } = counter;
reset();
text
Uncaught TypeError: Cannot set properties of undefined (setting 'count')
    at reset (http://127.0.0.1:8125/this.js:4:16)
    at http://127.0.0.1:8125/this.js:9:1

The line at reset (... this.js:4:16) is where execution stopped: the = in this.count = 0 inside reset. The line below it, this.js:9:1, shows that reset was called from line 9.

Because the extracted reset was called as a plain reset(), this was undefined. MDN's class documentation explains that when a method is stored in a variable and then called, this inside the method is undefined. Class bodies are always in strict mode, even without writing "use strict", so this behavior does not change.

If you want to extract a method and pass it around, use bind to create a function with this fixed.

js
const reset = counter.reset.bind(counter);
reset();
console.log("count:", counter.count);
text
count: 0

count changed from 5 to 0, and no error was raised.

?. cannot be used on the left side of an assignment

If you write ?. on the side where you assign a value, in the same way you would when reading with settings.theme?.color, you get a different error.

js
console.log("ファイルの1行目");
const settings = {};
settings.theme?.color = "blue";
text
Uncaught SyntaxError: Invalid left-hand side in assignment

This is a syntax error, so none of the code in the file runs. Even the first line (the console.log call at the top of the file) was not printed to the console. MDN's optional chaining documentation also states that assigning to an optional chain expression is invalid. If you want to set a value, create the container first, for example with ??= as shown above, and then assign.

Point

When you see Cannot set properties of undefined (setting 'x'), the thing just to the left of x is undefined. Most often it is a container object you have not created yet. Create that object before you set the value.

When the value on the left is null instead of undefined, the message changes to Cannot set properties of null (setting 'color') (I confirmed this by testing with settings = { theme: null }). The way to fix it is the same.

​Posted by 86