Are variable length arrays possible with Javascript Are variable length arrays possible with Javascript arrays arrays

Are variable length arrays possible with Javascript


Javascript arrays are not fixed-length; you can do anything you want to at any index.

In particular, you're probably looking for the push method:

var arr = [];arr.push(2);            //Add an elementarr.push("abc");        //Not necessarily a good idea.arr[0] = 3;             //Change an existing elementarr[2] = 100;           //Add an elementarr.pop();              //Returns 100, and removes it from the array

For more information, see the documentation.


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); // 101console.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); // 101arr.length -= 10;console.log(arr.length); // 91console.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); // 4294967295console.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


You can also use the Array() constructor.

const desiredLength = 5; // could be dynamically generatedconst list = new Array(desiredLength); // will be length 5

One caveat is that you will be unable to map the initial elements by using Array(n).map(). Instead, you can use Array.from() (Documentation).

const desiredLength = 5; // could be dynamically generatedconst passkeys = Array.from(Array(desiredLength), () => {    return Math.random().toString(32).substring(2, 10);});