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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With