Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an immutable Array?

I have tried to write an Array that the script cannot mutate; not by adding or popping elements from or to the Array. I tried to do something like this:

const arr = [30, 20, 10]

but when I tried to add an element to the Array it works.

Can someone please can show me how to define an array that cannot change

like image 457
Doron Shevach Avatar asked Jun 19 '26 15:06

Doron Shevach


1 Answers

You're looking for Object.freeze()

However, you should note that entries that are themselves Objects can still be modified, unless they are also frozen

const arr = [30, 20, 10, {name: 'Tom', age: 54}, [0]];
Object.freeze(arr);

// arr.push(10); // Uncaught TypeError: Cannot add property 3, object is not extensible
// arr.pop();    // Uncaught TypeError: Cannot delete property '2' of [object Array]

arr[0] = 5;

arr[3].name = 'Modified';
arr[4][0] = 'Modified';

console.log(arr);
like image 62
Shiny Avatar answered Jun 21 '26 05:06

Shiny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!