Is it possible, in Javascript, to create an array whose length is guaranteed to remain the same?
For example, the array A is created with length 2. Subs
The current answer is YES, you can. There are severals ways to do that, but some web browsers has it's own "interpretation".
var x = new Array(10).fill(0);
// Output: undefined
Object.freeze(x);
// Output: Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
x.push(11)
// Output: TypeError: can't define array index property past the end of an array with non-writable length
x.pop()
// Output: TypeError: property 9 is non-configurable and can't be deleted [Learn More]
x[0]=10
// Output: 10 // You don't throw an error but you don't modify the array
x
// Output: Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
Is important to notice that if the array are object, you need to do, deep freeze instead. The code of deepfreeze is here.
A Class that wraps an Array (it's better if you don't want to throw an exception)
With ES2015 code should work the follow solution but it doesn't:
var x = new Array(10).fill(0);
Object.freeze( x.length );
x.push(3);
console.log(x);