TypeError: Cannot set properties of Undefined in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
7 min

banner

# TypeError: Cannot set properties of Undefined in JavaScript

The "TypeError: Cannot set properties of undefined" occurs when setting a property on an undefined value.

To solve the error, make sure the value is of the expected type (object or array) before setting a property on it.

cannot set property of undefined

Here is an example of how the error occurs with objects.

index.js
const example = undefined; // ⛔️ TypeError: Cannot set properties of undefined (setting 'myKey') example.myKey = 'my value';

We tried to set a property on an undefined value which caused the error.

And here is an example of how the error occurs with arrays.

index.js
const example = undefined; // ⛔️ TypeError: Cannot set properties of undefined (setting '0') example[0] = 'my value';

cannot set properties of undefined with arrays

We tried to update the array element at index 0 on an undefined value which caused the error.

# Provide a fallback value for when the variable is undefined

To solve the error, provide a fallback value in case the variable is undefined.

Here is an example of providing a fallback value of an empty object when the variable is undefined.

index.js
const fromDb = undefined; const obj = fromDb || {}; obj.myKey = 'my value'; console.log(obj); // 👉️ {myKey: 'my value'}

provide fallback value when variable is undefined

The code for this article is available on GitHub

We used the logical OR (||) operator to provide a fallback value if the value to the left is falsy (e.g. undefined).

If the value to the left is falsy, the logical OR (||) operator returns the value to the right.

Here is how we can use the logical OR (||) operator to provide a fallback value of an empty array when the variable is undefined.

index.js
const fromDb = undefined; const arr = fromDb || []; arr[0] = 'my value'; console.log(arr); // 👉️ ['my value']

You can also use the nullish coalescing (??) operator to achieve the same result.

index.js
const fromDb = undefined; const obj = fromDb ?? {}; // 👈️ nullish coalescing obj.myKey = 'my value'; console.log(obj); // 👉️ {myKey: 'my value'}

If the value to the left of the nullish coalescing operator (??) is equal to null or undefined, the value to the right is returned, otherwise, the value to the left of the operator is returned.

If the fromDb variable stores an undefined or a null value, an empty object is returned.

# Checking if the variable is not undefined before setting a property

You can also use a simple if statement to check if the variable is not undefined before setting the property.

index.js
const obj = undefined; if (obj != undefined) { obj.property = 'value'; } console.log(obj); // 👉️ undefined

checking if the variable is not undefined before setting property

The code for this article is available on GitHub

The if block is only run if the variable doesn't store an undefined value.

# Setting nested properties on undefined values in Objects or Arrays

The error most commonly occurs when trying to set a nested property on an undefined value in an object or array.

index.js
const obj = {}; // ⛔️ Cannot set properties of undefined (setting 'b') obj['a']['b'] = 'my value'; const arr = []; // ⛔️ Cannot set properties of undefined (setting '0') arr[0][0] = 'my value';

Trying to access obj['a'] returns undefined because the a key doesn't exist in the object.

Similarly, accessing the array at index 0 returns an undefined value because there is no element at that index in the array.

When we try to set the property or index on an undefined value, the error occurs.

To solve the error, make sure the object or array you're trying to set a property on exists.

Here's an example that does that for objects.

index.js
const obj = {}; if (obj['a']) { obj['a']['b'] = 'my value'; } else { obj['a'] = { b: 'my value', }; } console.log(obj); // 👉️ {a: {b: 'my value'}}

make sure the object or array exists

The code for this article is available on GitHub

If accessing the a property on the object returns an undefined value, we set the a property to an object that contains the b property.

And if the a property is defined on the object, we set the b property to be equal to my value.

Here's the same example but for two-dimensional arrays.

index.js
const arr = []; if (Array.isArray(arr[0])) { arr[0][0] = 'my value'; } else { arr[0] = ['my value']; } console.log(arr); // 👉️ [ ['my value'] ]

We first check if the array element at index 0 is an array. If the condition is met, we set its value at index 0 to my value.

If the array element at index 0 is not an array, we set it to an array that contains the value.

# Make sure to specify the required arguments when calling functions

The error might also occur if you're supposed to pass an object or an array as an argument to a function, but don't provide it.

index.js
function example(obj) { obj.first = 'John'; obj.last = 'Smith'; return obj; } // ⛔️ Cannot set properties of undefined (setting 'first') example();
The function expects an object argument, however, we didn't supply one, so the value of obj is undefined in the function and the error is caused.

You can set a default value for the obj parameter to resolve the issue.

index.js
// 👇️ Provide an empty object as a default value function example(obj = {}) { obj.first = 'John'; obj.last = 'Smith'; return obj; } const result = example(); console.log(result); // 👉️ {first: 'John', last: 'Smith'}

set default value for object parameter

The code for this article is available on GitHub

We set an empty object as the default value for the obj parameter.

If an argument isn't passed when the function is invoked, the obj variable defaults to an empty object.

Make sure you haven't forgotten to use the return statement because functions that don't return a value return undefined.

# Make sure to place the JS script tag at the bottom of the body tag

When working in a browser environment, make sure to place the JS script tag at the bottom of the body tag after the DOM elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>

Now you will be able to access the DOM elements in your index.js file.

index.js
const boxes = document.getElementsByClassName('box'); // HTMLCollection(3) [div.box, div.box, div.box] console.log(boxes); console.log(boxes[0]); // 👉️ div.box boxes[0].style.color = 'red';

HTML code is parsed from top to bottom, so if you place the JS script tag above the DOM elements it tries to access, they won't be available in your index.js file.

If you need to iterate over a collection and set a property on each element, use the Array.forEach() method.

index.js
// 👇️ convert to Array const boxes = Array.from(document.getElementsByClassName('box')); // 👇️ iterate over array boxes.forEach(element => { element.style.color = 'red'; });

We used the Array.from() method to convert the HTML Collection to an array and used the Array.forEach() method to iterate over the array and set a property on each element.

You can also use the for...of loop to iterate over a collection and set a property on each element.

index.js
const boxes = document.getElementsByClassName('box'); for (const element of boxes) { element.style.color = 'red'; }

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

Here is an example of solving the error for a specific property in a browser environment.

# Cannot set properties of undefined (setting 'display')

The "TypeError: Cannot set properties of undefined (setting 'display')" error occurs when trying to set the display property on an undefined value.

To solve the error, make sure you access the display property after accessing the style property on a valid DOM element.

Here's an example of how the error occurs.

index.js
const elements = []; // ⛔️ Uncaught TypeError: Cannot set properties of undefined (setting 'display') elements[0].display = 'block';

cannot set property display of undefined

Here's the HTML code for a working example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="container">Content 1</div> <div class="container">Content 2</div> <div class="container">Content 3</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Notice that we placed the script below the code that creates the div elements. Had we placed the script above the DOM elements, we wouldn't be able to access them inside the index.js file.

Here's the related JavaScript code.

index.js
const elements = document.getElementsByClassName('container'); console.log(elements); // 👉️ [div.container, div.container, div.container] // ✅ Update display property of first element elements[0].style.display = 'block'; // ✅ Update display property for all elements in the NodeList for (const element of elements) { element.style.display = 'block'; }

We used the getElementsByClassName method to get an array-like object that contains the DOM elements with a class of container.

The first example shows how to update the display property on the first element in the Node list. We access the element at position 0 and update the property directly.

If you need to set the display property for all of the elements with a specific class, use a for...of loop to iterate over the array-like objects.

index.js
const elements = document.getElementsByClassName('container'); console.log(elements); // 👉️ [div.container, div.container, div.container] // ✅ Update display property for all elements in the NodeList for (const element of elements) { element.style.display = 'block'; }

On each iteration, we set the display property of the element to block.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.