Categories
JavaScript Answers

How to Fix the ‘TypeError: can’t delete non-configurable array element’ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘TypeError: can’t delete non-configurable array element’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘TypeError: can’t delete non-configurable array element’ when we’re developing JavaScript apps.

Fix the ‘TypeError: can’t delete non-configurable array element’ When Developing JavaScript Apps

To fix the ‘TypeError: can’t delete non-configurable array element’ when we’re developing JavaScript apps, we should make sure we aren’t trying to shorten an array with entries that aren’t configurable.

For instance, we’ll get the error if we write:

"use strict";
const arr = [];
Object.defineProperty(arr, 0, {value: 0});
Object.defineProperty(arr, 1, {value: "1"});

arr.length = 1;

since both entries are non-configurable.

We’ll also get the error if we write:

"use strict";
const arr = [1,2,3];
Object.seal(arr);

arr.length = 1;

to seal the array with Object.seal.

Instead, we write:

"use strict";
var arr = [];
Object.defineProperty(arr, 0, {value: 0, configurable: true});
Object.defineProperty(arr, 1, {value: "1", configurable: true});

arr.length = 1;

to make the entries configurable.

Or make a copy of the sealed array and then modify it:

"use strict";
const arr = [1,2,3];
Object.seal(arr);

const copy = [...arr];
copy.length = 1;

Conclusion

To fix the ‘TypeError: can’t delete non-configurable array element’ when we’re developing JavaScript apps, we should make sure we aren’t trying to shorten an array with entries that aren’t configurable.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *