Are variable length arrays possible with Javascript

29,903

Solution 1

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 element
arr.push("abc");        //Not necessarily a good idea.
arr[0] = 3;             //Change an existing element
arr[2] = 100;           //Add an element
arr.pop();              //Returns 100, and removes it from the array

For more information, see the documentation.

Solution 2

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
Share:
29,903
Ankur
Author by

Ankur

A junior BA have some experience in the financial services industry. I do programming for my own personal projects hence the questions might sound trivial.

Updated on October 06, 2020

Comments

  • Ankur
    Ankur over 3 years

    I want to make a variable length array in Javascript.

    Is this possible. A quick google search for "Javascript variable length array" doesn't seem to yield anything, which would be surprising if it were possible to do this.

    Should I instead have a String that I keep appending to with a separator character instead, or is there a better way to get a varible length array-like variable.

  • Scott Uphus
    Scott Uphus over 2 years
    why is arr.push("abc"); not a good idea?