How to Create and Manipulate Arrays in JavaScript

Share this article

Learn how to work with JavaScript arrays. We’ll cover the array creation process, changing the length of an array, as well as adding, removing, and replacing entries, 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);
  });
};
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!

Creating an Array in JavaScript

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 a length equal to the number of numbered properties is a dense array.
//Creates an array with no numbered entries

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

var arr = [];
arr.length = 5;
test(arr);
// 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'];
test(arr);
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = [undefined, undefined, undefined, undefined, undefined];
test(arr);
// 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 of an Array in JavaScript

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'];
test(arr);
// length:6, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

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

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

arr.length = 7;
test(arr);
// 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 from Arrays in JavaScript

JavaScript provides three methods pop, shift, and splice that can remove entries from the array and, therefore, reduce the array’s length. 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

How to Add Entries to Arrays

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) to insert new entries and, where necessary, move the old ones.
var arr = ['a','b','c','d','e','f',,,'i'];
arr[11] = 'l';
test(arr);
// 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',,,,];
arr.push('j');
test(arr);
// 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',,,,];
arr.unshift('x');
test(arr);
// 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 in JavaScript Arrays

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, 4:e, 5:f, 6:g, 7:h, 8:i
test(arr2); // length:2

Conclusion

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.

Frequently Asked Questions (FAQs) about JavaScript Arrays

How can I add elements to an array in JavaScript?

In JavaScript, you can add elements to an array using the push() method. This method adds new items to the end of an array and returns the new length. Here’s an example:

let fruits = ["apple", "banana"];
fruits.push("mango");
console.log(fruits); // ["apple", "banana", "mango"]

How can I remove elements from an array in JavaScript?

JavaScript provides several methods to remove elements from an array. The pop() method removes the last element from an array and returns that element. The shift() method removes the first element from an array and returns that element. Here’s how you can use these methods:

let fruits = ["apple", "banana", "mango"];
let last = fruits.pop();
console.log(last); // "mango"
let first = fruits.shift();
console.log(first); // "apple"

How can I sort an array in JavaScript?

JavaScript provides the sort() method for sorting the elements of an array. By default, the sort() method sorts elements as strings. Here’s an example:

let fruits = ["banana", "apple", "mango"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "mango"]

How can I reverse an array in JavaScript?

The reverse() method in JavaScript reverses the order of the elements in an array. Here’s how you can use it:

let fruits = ["apple", "banana", "mango"];
fruits.reverse();
console.log(fruits); // ["mango", "banana", "apple"]

How can I join two arrays in JavaScript?

JavaScript provides the concat() method to join two or more arrays. This method does not change the existing arrays but returns a new array. Here’s an example:

let fruits1 = ["apple", "banana"];
let fruits2 = ["mango", "orange"];
let allFruits = fruits1.concat(fruits2);
console.log(allFruits); // ["apple", "banana", "mango", "orange"]

How can I find an element in an array in JavaScript?

JavaScript provides the includes() method to check if an array contains a certain element. This method returns true if the array contains the element, and false otherwise. Here’s how you can use it:

let fruits = ["apple", "banana", "mango"];
console.log(fruits.includes("apple")); // true
console.log(fruits.includes("grape")); // false

How can I convert an array to a string in JavaScript?

The join() method in JavaScript joins all elements of an array into a string. The elements will be separated by a specified separator. The default separator is a comma (,). Here’s an example:

let fruits = ["apple", "banana", "mango"];
let str = fruits.join();
console.log(str); // "apple,banana,mango"

How can I loop through an array in JavaScript?

JavaScript provides several ways to loop through an array. The most common way is using a for loop. Here’s an example:

let fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

How can I create a multidimensional array in JavaScript?

In JavaScript, you can create a multidimensional array by creating an array of arrays. Here’s an example:

let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(matrix[0][0]); // 1

How can I copy an array in JavaScript?

JavaScript provides several ways to copy an array. One way is using the slice() method. This method returns a shallow copy of a portion of an array. Here’s how you can use it:

let fruits = ["apple", "banana", "mango"];
let copy = fruits.slice();
console.log(copy); // ["apple", "banana", "mango"]

Stephen ChapmanStephen Chapman
View Author

I have been teaching JavaScript for many years. Between 2004 and 2011 I provided all the JavaScript pages for About.com. In 2011 I created http://javascriptexample.net which teaches introductory through intermediate JavaScript. I have also taught JavaScript classes at the local community college.

arrayarray manipulationarray methods
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week