Last updated: Mar 2, 2024
Reading time·7 min
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.
Here is an example of how the error occurs with objects.
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.
const example = undefined; // ⛔️ TypeError: Cannot set properties of undefined (setting '0') example[0] = 'my value';
We tried to update the array element at index 0
on an undefined
value which
caused the error.
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
.
const fromDb = undefined; const obj = fromDb || {}; obj.myKey = 'my value'; console.log(obj); // 👉️ {myKey: 'my value'}
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
.
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.
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.
undefined
before setting a propertyYou can also use a simple if
statement to check if the variable is not
undefined
before setting the property.
const obj = undefined; if (obj != undefined) { obj.property = 'value'; } console.log(obj); // 👉️ undefined
The if
block is only run if the variable doesn't store an undefined
value.
The error most commonly occurs when trying to set a nested property on an
undefined
value in an object or array.
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.
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.
const obj = {}; if (obj['a']) { obj['a']['b'] = 'my value'; } else { obj['a'] = { b: 'my value', }; } console.log(obj); // 👉️ {a: {b: 'my value'}}
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.
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
.
0
is not an array, we set it to an array that contains the value.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.
function example(obj) { obj.first = 'John'; obj.last = 'Smith'; return obj; } // ⛔️ Cannot set properties of undefined (setting 'first') example();
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.
// 👇️ 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'}
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
.
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.
<!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.
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.
// 👇️ 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.
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.
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.
const elements = []; // ⛔️ Uncaught TypeError: Cannot set properties of undefined (setting 'display') elements[0].display = 'block';
Here's the HTML code for a working example.
<!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>
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.
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.
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
.
You can learn more about the related topics by checking out the following tutorials: