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

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:


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:


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:


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe