Skip to content
the poor coder

Cannot assign to read only property '0' of object '[object Array]'

Poor Man
Published
Reading time
2 min read

Cannot assign to read only property '0' of object '[object Array]'#

This error occurs when trying to modify a read-only property of an array. In JavaScript, arrays are objects and some properties of the array may be read-only. When trying to modify such properties, this error is thrown.

Let's take a look at an example:

Text

const arr = ['one', 'two', 'three'];
arr[0] = 'new value'; // This will work
arr[0][1] = 'x'; // This will throw "Cannot assign to read only property '0' of object '[object Array]'"

In the above example, we are trying to modify the second character of the first element of the array. But the first element is a string and strings are immutable in JavaScript. So, this will throw the error we are discussing.

How to Fix#

To fix this error, we need to avoid modifying read-only properties. If we want to modify an element of an array, we should make sure it is not a read-only property.

We can also use the spread operator to create a new array instead of modifying the existing one:

Text

const arr = ['one', 'two', 'three'];
const newArr = [...arr]; // Creates a new array with the same elements
newArr[0] = 'new value'; // This will work
newArr[0][1] = 'x'; // This will not throw any error

Another way to avoid this error is to use Object.freeze() method to make the array read-only:

Text

const arr = Object.freeze(['one', 'two', 'three']);
arr[0] = 'new value'; // This will throw "Cannot assign to read only property '0' of object '[object Array]'"

By using the Object.freeze() method, we can make sure that no one can modify the array, including its read-only properties.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC