Yes, variable-length arrays are possible with Javascript's Array prototype. As SLaks noted, you can use .push()
and .pop()
to add and remove items from the end of the array respectively and the array's length property will increase and decrease by 1 respectively each time.
You can also set the value of a specific index in an array like so:
const arr = [];
arr[100] = 'test';
console.log(arr[100]); // 'test'
console.log(arr.length); // 101
console.log(arr[99]); // undefined
Every other array index besides index 100
will be undefined
.
You can also adjust the array's length by simply setting the array's length property, like so:
const arr = [];
arr[100] = 'test';
arr.length = 1000;
console.log(arr[100]); // 'test'
console.log(arr.length); // 1000
Or...
const arr = [];
arr[100] = 'test';
console.log(arr.length); // 101
arr.length -= 10;
console.log(arr.length); // 91
console.log(arr[100]); // undefined
The maximum value that an array's length property can be is 4,294,967,295. Interestingly though, you can set values of an array at indices larger than 4,294,967,295:
const arr1 = [];
const arr2 = [];
arr1[4294967294] = 'wow';
arr2[4294967295] = 'ok?';
console.log(arr1[4294967294]); // 'wow'
console.log(arr1.length); // 4294967295
console.log(arr2[4294967295]); // 'ok?'
console.log(arr2.length); // 0
If you try to set length a number larger than 4,294,967,295 it will throw a RangeError:
const arr = [];
arr.length = 4294967296;
console.log(arr.length); // RangeError: Invalid array length
arr.push("abc");
not a good idea? – Meal