Quick Tip: How to Create and Manipulate Arrays in JavaScript

By Stephen Chapman

This article was peer reviewed by Chris Perry and Marcello La Rocca. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

The length property of Array objects is one that many who are relatively new to JavaScript do not understand. Many mistakenly believe that the length tells you exactly how many entries there are in an array whereas this is only true of some arrays. Some beginners do not even realize that length is a writable property of arrays. To clarify just exactly how the length property works, let’s take a look at what happens when we either change its value ourselves or run something that updates the array that also results in the length changing.

Let’s start at the beginning. A JavaScript array has a property called length and optionally has numbered properties with names between 0 and 4294967294 inclusive. It also has a number of methods for manipulating the properties some of which we will look at as a part of our examination of how the length property works. Note that JavaScript does not support associative arrays and so while you can add named properties to an array, they do not form a part of the array and will be ignored by all the array methods. They also will not affect the length.

To make it easier to show exactly what happens to the array properties as we process various statements, we will run the following function after each piece of code. This will log the length of the array and all of the numbered properties to the browser’s console.

var test = function(array) {
  console.log('length:'+ array.length);
  array.forEach(function(element, index, array) {
    console.log(index + ':' + element);

Creating an Array

We will begin by looking at different ways to create an array in JavaScript. The first two of these examples create arrays where only the length is set and there are no numbered entries at all. The second two create numbered entries from 0 to one less than the length.

An array where the length is greater than the amount of numbered properties is known as a sparse array while one with the length equal to the number of numbered properties is a dense array.

//Creates an array with no numbered entries

var arr = new Array(5);
// length: 5

var arr = [];
arr.length = 5;
// length: 5

Note that the array literal notation (where you define a new array using just empty brackets) is preferred when creating new arrays.

var arr = ['a', 'b', 'c', 'd', 'e'];
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = [undefined, undefined, undefined, undefined, undefined];
// length:5, 0:undefined, 1:undefined, 2:undefined, 3:undefined, 4:undefined

The array methods that process the numbered properties (forEach in our case) will only process those that exist. If you instead process the array using a for or while loop then the loop will also attempt to process those properties that don’t exist and the array will identify those entries that don’t exist as being undefined. Your code would then be unable to distinguish between the last of the above examples and the first two. You should always use the array methods for processing an array where you are not certain that you are dealing with a dense array.

Changing the Length

The following examples look at what happens if we set a new length for the array that is less than the current length.

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
// length:6, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

arr.length = 5;
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = ['a','b','c','d','e','f',,,];
// length:8, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

arr.length = 7;
// length:7, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

Note that when creating an array using [] notation each entry consists of a value followed by a comma. Where the value is omitted then no property is created for that position. The last comma may only be omitted if there is a value supplied for that property as otherwise the length will be reduced by one.

Removing Entries

JavaScript provides three methods pop, shift and splice that can remove entries from the array and which therefore reduce the length of the array. In each case the value (or values) removed are returned by the call.

// pop() removes the last element from an array
var arr = ['a','b','c','d','e','f'];
var el = arr.pop();
test(arr); // length:5, 0:a, 1:b, 2:c, 3:d, 4:e
console.log(el); // f

// shift() removes the first element from an array
var arr = ['a','b','c','d','e','f'];
var el = arr.shift();
test(arr); // length:5, 0:b, 1:c, 2:d, 3:e, 4:f
console.log(el); // a

// splice() can remove existing elements
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1.splice(0,2); // remove 2 elements starting at index 0
test(arr1); // length:4, 0:c, 1:d, 2:e, 3:f
test(arr2); // length:2, 0:a, 1:b

var arr1 = ['a','b','c','d','e','f',,,'i'];
var arr2 = arr1.splice(6,2); // remove 2 elements starting at index 6
test(arr1); // length:7, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f, 6:i
test(arr2); // length:2

Adding Entries

We can add a new entry into an array simply by specifying a position in the array for which a numbered property does not yet exist. We can also use one of the three methods JavaScript provides (push, unshift and splice) for inserting new entries and, where necessary, moving the old ones.

var arr = ['a','b','c','d','e','f',,,'i'];
arr[11] = 'l';
// length:12, 0:a, 1:b, 2:c, 3:d, 5:f, 8:i, 11:l

// push() adds one or more elements to the end of an array
var arr = ['a','b','c','d','e','f',,,,];
// length:10, 0:a, 1:b, 2:c, 3:d, 5:f, 9:j

// unshift() adds one or more elements to the beginning of an array
var arr = ['a','b','c','d','e','f',,,,];
// length:10, 0:x, 1:a, 2:b, 3:c, 4:d, 5:e, 6:f

arr1 = ['a','b','c','d','e','f',,,'i'];
arr2 = arr1.splice(6,0,'g','h'); // removes 0 elements from index 6, and inserts 'g', 'h'
test(arr1); // length:11, 0:a, 1:b, 2:c, 3:d, 5:f, 6:g, 7:h, 10:i
test(arr2); // length:0

Replacing Entries

Where we assign a new value to an entry that already exists, then that entry simply gets a new value and the rest of the array is unaffected. Also by combining the variants of the splice() method that we have already looked at we can replace existing entries or fill gaps in the array.

var arr1 = ['a','b','c','d','e','f',,,'i'];
var arr2 = arr1.splice(6,2,'g','h');
test(arr1); // length:9, 0:a, 1:b, 2:c, 3:d, 5:f, 6:g, 7:h, 8:i
test(arr2); // length:2


The above examples should have given you a better idea of how the length property of an array works. This can be greater or equal to the number of entries in the array. Where it is equal we have a dense array and where it is greater we have a sparse array. Exactly what a particular array method does can depend on whether there is actually a property corresponding to a given position in a sparse array. If we change the length of an array it removes any numbered properties in the array that are in positions that are greater than the new length. If the length was equal to the amount of numbered properties and we increase the length then we convert a dense array to a sparse one. The array methods for deleting and adding properties in the array will move the existing entries around where necessary and will also retain and move any gaps between the properties.

  • hidran arias

    array length will be the highest index plus 1:
    var arr=[];
    arr[47] =2;
    console.log(arr.length);// 48

    • Steve

      That’s part of the first example under ‘Adding Entries’ except that in the article it uses 11 & 12 where you use 47 & 48 to demonstrate the same thing.

      • hidran arias

        Yes, you’re right! but I thought that stating that the array length property is the highest index plus one was clearer.

        • Steve

          But your statement is only true for that particular example where an index is assigned that is greater than the current length. The array length can be any number higher than the index of the highest existing index up to and including 4294967294. If the length was already 10000 then adding an entry at position 47 would.t change the length even if there wasn’t a position 47 before you added it.

          var arr=[];
          arr.length = 10000;
          console.log(arr.length); // 10000

          In both your example and this one the array only contains one value but your’s changes the length as it adds the first value where mine doesn’t because the array already has enough holes to insert the first entry in that spot without changing the length.

          • hidran arias

            Yes, it is true. My statement is for a normal case where length property is not manually modified . I had a real case where an array was cicled hundreds of times because of its having an index key of 815 but it really had seven entries.this a real life bug and it was then that I discovered and never forgot that.It wouldn’t have been a problem for a forEach function but it was a plain for.

          • Steve

            Your statement isn’t even always true when the length isn’t manually modified.

            Just using – new Array(10000); – to create the array means that the length will be 10000 unless you add entries past that point even though defining the array that way means that it doesn’t contain any entries until you add some. Even defining an array using [,,,,,] means the array has a length of 5 and is empty and the length hasn’t been modified there either.

            The only thing you can say about the length of an array is that it will be greater than or equal to the number of entries the array contains.

          • hidran arias

            Thanks for the further explanation as arrays are pretty weird in javascript, mainly when people use non numerical keys.

            If we consider undefined elements as non elements then new Array(10000) is empty but if we use a for cycle, it will output 10 000 undefined slots and the last index will be 9999 . So, considering the last undefined output value as a value, then the highest index plus one holds true also in this case.

            My practical point is this:
            Even if you declare var arr = new Array(10000) and don’t push any elements into it and you use , say, a for cycle to make an Ajax request for every element of the array by using array.length ( without verifying that its values are not undefined) 10 000 calls will be made.

            Thanks again Steve!. I hope you write some more articles like this one!

          • Steve

            The elements that are undefined still exist – see the fourth example above. There is a difference between entries in an array that are undefined and ones that don’t exist.

            for example:

            (new Array(6)).forEach(function(x) console.log(x);});

            will write nothing to the console because none of the possible 6 entries in the array actually exist.

            Array.apply(null, Array(6)).forEach(function(x) console.log(x);});

            will write undefined to the console 6 times because this time the entries do exist but are yet to be assigned a value.

            In both cases the length is 6 but only in the second of these do the 6 entries actually exist (but without having had a value assigned to them yet). The first of these contains zero entries and not 6.

          • hidran arias

            So, Array.apply(null, Array(6)) is the same as:
            var t = [undefined, undefined, undefined, undefined, undefined, undefined];
            I understand better the difference now!

  • Austin Wulf

    This is great! Wondering why you didn’t cover methods like map, filter, reduce and the like?

    • Steve

      The title of the article got changed after I wrote it. The original title better indicated that it is a discussion of how the length property works. Had I been writing an article on creating arrays it would have been several times as long.

  • Steve

    As this article was originally intended to only deal with the length of arrays and not the broader topic of creating arrays, one significant command for creating arrays got left out.

    Array.apply(null, Array(5));

    This creates [undefined,undefined,undefined,undefined,undefined] instead of [,,,,,]

    You can therefore apply the map method to it to load values based on whatever criteria you have in the callback function because the array doesn’t contain any holes for the map to skip over.

  • gutterboy

    What a timely article……… have recently been having a lot of trouble understanding the splice method and looping through sparse arrays and this article has shone the light on them. Thanks a lot!

  • Kenneth Davila

    So cool to see you over the years contributing your input to the community. Man I don’t know on how many sites I have seen that avatar. hahaha…

  • JoaoReynolds

    You left out slice, which is useful to know vs splice:

    var x = [a, b, c];
    var y = x.slice(1, 2);
    console.log(x); // [a, b, c]
    console.log(y); // [b]

  • Jubayer Arefin

    Nice article. There is a typo though. You left out 4:e in 3rd line of “Replacing Entries” section.



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.