An array is a list-like object in JavaScript that can be used to store multiple values in a single variable. It is an ordered-collection of values where each value is called an element that has a pre-defined numeric position in the array, referred to as its index.

A JavaScript array can store different kinds of data types in one single box: strings, boolean, numbers, HTML elements, objects, or even other arrays. It means you can create an array that has an HTML element stored in the first position, an object in the second, a string in the third, and so on.

Just like other programming languages like Java and Python, arrays in JavaScript are zero-based. It means that the first element in the array has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.

Creating an Array

There are two ways to create an array in JavaScript. The simplest way to create an array is by using the array literal notation:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

Alternatively, you could use the global Array class constructor to initialize a new array:

const fruits = new Array('Apple', 'Orange', 'Mango', 'Banana');

Both of the above examples do the same thing. Almost all the time, for the sake of simplicity and readability, the array literal syntax is used to create a new array.

To create an empty array, just use the empty brackets:

const animals = [];

Spaces and line-breaks are permitted. An array declaration can span on multiple lines:

const fruits = [
    'Apple',
    'Orange',
    'Mango',
    'Banana'
];

If you know in advance the number of elements the array will contain, you can use the count as an argument to the Array constructor. An empty array will automatically be created with the specified number of slots initialized with the value undefined:

const numbers = new Array(50);

An array can store elements of any type: strings, numbers, functions, objects, and even other arrays:

const arr = [
    'Tiger',
    29.6,
    { name: 'John Doe', age: 29 },
    true,
    function () {
        console.log('Hey there!');
    },
    ['Apple', 'Banana']
];

Accessing Elements of an Array

You can access an array element by its index number in square brackets:

const animals = ['🐱', '🐭', '🐧', '🐯', '🐘'];

console.log(animals[1]); // 🐭
console.log(animals[3]); // 🐯

Note that an array index starts at 0, and not 1. This means that the first element has an index of 0, and the last element has an index of array length minus 1. The above array of five elements has indexes starting from 0 to 4.

A JavaScript array can be multi-dimensional, which means that an array element can contain another array, whose elements can contain arrays, and so on. To access an element from a multi-dimensional array, you need to specify the index multiple times:

const users = [
    ['John Doe', 22],
    ['Lisa Lee', 33],
    [
        ['Alex', 'USA'],
        ['Tom Doe', 'DE']
    ]
];

console.log(users[1][0]); // Lisa Lee
console.log(users[2][0]); // ['Alex', 'USA']
console.log(users[2][1][0]); // Tom Doe

Adding Elements to an Array

The simplest way to add an element to an array is by using the push() method:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// add a new element
fruits.push('Cherry');

console.log(fruits); // ['Apple', 'Orange', 'Mango', 'Banana', 'Cherry']

Alternatively, you could use the length property to insert an element at the end of the array:

fruits[fruits.length] = 'Cherry';

Changing an Array Element

The following example demonstrates how you can change the value of an array element:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// change 2nd element value
fruits[1] = 'Cherry';

// print array
console.log(fruits); // [ 'Apple', 'Cherry', 'Mango', 'Banana' ]

Deleting Elements from an Array

Since JavaScript arrays are objects, you can use the delete operator to delete any specific element from an array:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// delete 2nd element
delete fruits[1];

console.log(fruits); // ['Apple', <1 empty item>, 'Mango', 'Banana']

Since the delete operator only resets the value of the element to undefined, you shouldn't use it as it might leave holes in the array. Instead, you should use pop() and shift() methods explained below.

Detecting an Array

One of the most common questions asked in JavaScript communities is how to determine whether the given variable is an array.

The main problem is that a JavaScript array is internally treated as a special kind of object. The square brackets syntax used for accessing an array element arr[index] is essentially the same as we use for an object obj[key]. The only visible difference is that numbers are used as keys.

Therefore, you can not use the typeof operator as it would always return object for an array:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

console.log(typeof fruits); // object

To truly determine whether the given variable is an array, ECMAScript 5 introduced a new method called Array.isArray():

Array.isArray(fruits); // true

Array.isArray() works in all modern browsers as well as Internet Explorer 9 and higher. Alternatively, you could also use the instanceof operator to check whether the given object is an array:

fruits instanceof Array; // true

The instanceof operator is supported by Internet Explorer 6 and higher.

The length Property

The length property of an array returns the largest numeric index plus one, and not the actual count of the elements. It automatically updates when the array is modified.

Let us look at the following example to understand what I mean:

const animals = [];
animals[20] = 'Cat';

console.log(animals.length); // 21

As you can see above, the array's length property is updated to the highest index plus one when we added just a single element. From the performance perspective, it is very useful because the actual elements are not counted whenever we modify the array.

Another interesting thing about the length property is that it is writable. You can manually set a new value to increase or decrease the size of the array. An array can be truncated by setting a smaller length value:

const numbers = [1, 2, 3, 4, 5];

// truncate to 3 elements
numbers.length = 3;

console.log(numbers);   // [1, 2, 3]

// increase size to 6
numbers.length = 6;

console.log(numbers);   // [1, 2, 3, empty × 3]

To clear an array, simply set the length property value to 0:

// clear the array
numbers.length = 0;

console.log(numbers); // []

Looping an Array

There are multiple ways to iterate over array elements. The simplest way is to use the classic for loop:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

You also use other JavaScript loops like for...of, for...in, and forEach() to iterate through an array. Take a look at this article to learn more about all available ways of looping an array in JavaScript.

Array Methods

The array prototype provides several methods to perform traversal and mutation operations like add, remove, update, and more to arrays. Let us look at some of the most popular such methods that you can use to manipulate arrays.

toString()

The JavaScript toString() method converts an array to a comma-separated string:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

console.log(fruits.toString()); // Apple,Orange,Mango,Banana

join()

The join() method concatenates all array elements into a string. It is very much similar to the above toString() method, but allows you to specify a separator:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

console.log(fruits.join('_')); // Apple_Orange_Mango_Banana

concat()

The concat() method creates a new array by merging two existing arrays:

const arr1 = [1, 2];
const arr2 = [3, 4];

const newArr = arr1.concat(arr2);

console.log(newArr); // [ 1, 2, 3, 4 ]

The concat() method doesn't change the existing arrays. Instead, it always returns a new array. You can even specify more than one array arguments:

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];

const newArr = arr1.concat(arr2, arr3);

console.log(newArr); // [ 1, 2, 3, 4, 5, 6 ]

You can also use the concat() method to create a new array from an existing array with additional elements:

const arr1 = [1, 2];

const newArr = arr1.concat(2, 3, 4);

console.log(newArr); // [ 1, 2, 2, 3, 4 ]

push()

The push() method adds one or more elements at the end of an existing array:

const names = ['Alex', 'Mike', 'Atta'];

// add more elements
names.push('Ali', 'Emma');

console.log(names); // ['Alex', 'Mike', 'Atta', 'Ali', 'Emma']

The push() method returns the updated length of the array:

const length = names.push('Ali', 'Emma');

console.log(length); // 5

pop()

The pop() method does the opposite of the push() method. It removes the last element of an array and returns it:

const names = ['Alex', 'Mike', 'Atta'];

// remove last element
const elem = names.pop();

console.log(elem); // Atta

unshift()

The unshift() method adds one or more elements at the beginning of an array and unshifts older elements. This method returns the updated length of the array:

const names = ['Alex', 'Mike', 'Atta'];

// add new elements at start
const length = names.unshift('Ali', 'Emma');

console.log(length); // 5
console.log(names); // ['Ali', 'Emma', 'Alex', 'Mike', 'Atta']

shift()

The shift() method removes the first element of an array and returns it. All other elements are shifted to a lower index:

const names = ['Alex', 'Mike', 'Atta'];

// remove an element from start
const elem = names.shift();

console.log(elem); // Alex
console.log(names); // ['Mike', 'Atta']

splice()

The splice() method can be used to add new elements as well as remove existing elements from an array. This method changes the original array and returns the removed element(s) if any.

Here is the syntax of splice():

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  • start — The starting index for changing elements in the array.
  • deleteCount — An integer indicating the number of elements in the array to remove from start.
  • item1, item2, ... — The elements to be added to the array, beginning from start.

Removing Elements

Here is example that uses splice() to remove first two elements from the beginning of an array:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// remove first elements
const removed = fruits.splice(0, 2);

console.log(fruits); // ['Mango', 'Banana']
console.log(removed); // ['Apple', 'Orange']

If the deleteCount is omitted, all the elements starting from start are removed from the array:

const removed = fruits.splice(1);

console.log(fruits); // ['Apple']
console.log(removed); // ['Orange', 'Mango', 'Banana']

You can also replace the removed items with the new one by using splice():

const removed = fruits.splice(1, 2, 'Cherry', 'Watermelon');

console.log(fruits); // ['Apple', 'Cherry', 'Watermelon', 'Banana']
console.log(removed); // ['Orange', 'Mango']

Adding Elements

To add new elements with splice(), just set the deleteCount to zero:

const removed = fruits.splice(2, 0, 'Cherry');

console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed); // []

slice()

The slice() method slices out a part of an array into a new array. This method returns a new array with elements copied from the original array. The original array remains unchanged.

The slice() method takes up to two arguments: the start index to select elements from and an optional end index (exclusive).

Here is an example:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const sliced = fruits.slice(1, 3);

console.log(sliced); // ['Orange', 'Mango']

If the end index is omitted, slice() will slice out the rest of the array beginning from the start index:

const sliced = fruits.slice(1);

console.log(sliced); // ['Orange', 'Mango', 'Banana']

indexOf()

The indexOf() method searches the array for the given element, and returns its position:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

fruits.indexOf('Orange'); // 1
fruits.indexOf('Cherry'); // -1 (not found)

filter()

The filter() method creates a new array populated with all array elements that pass a certain condition:

const ages = [24, 45, 33, 76, 55, 86];

const above50 = ages.filter(age => age > 50);

console.log(above50); // [76, 55, 86]

The filter() method doesn't execute the function for empty elements. Also, it doesn't change the original array.

Note: In the above example, I have used an arrow function to filter elements. Arrow functions are part of ES6 and if you don't know about them, take a look at this guide.

map()

The map() method creates a new array with the results of executing a function for each element in the array:

const prices = [10, 9.99, 15, 45];

const updated = prices.map(price => '$' + price);

console.log(updated); // ['$10', '$9.99', '$15', '$45']

reduce()

The reduce() method reduces the array to a single value. It calls the provided method for each element of the array left to right except empty values. The return value of the function is stored in an accumulator.

The reduce() method is commonly used for calculating totals like sum, average, minimum and maximum values in an array.

Here is an example that calculates the sum of all elements in an array by using the reduce() method:

const numbers = [10, 99, 75, 45, 33];

const sum = numbers.reduce((total, num) => total + num);

console.log(sum); // 262

You can also pass an optional initial value of accumulator to the reduce() method:

// pass initial value 100
const sum = numbers.reduce((total, num) => total + num, 100);

console.log(sum); // 362

forEach()

The forEach() method iterates over all elements of an array by calling a function once for each element, in order:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

fruits.forEach((fruit, index) => {
    console.log(`${fruit} has ${index} index.`);
});

// Apple has 0 index.
// Orange has 1 index.
// Mango has 2 index.
// Banana has 3 index.

Take a look at this guide to learn more about forEach() method in JavaScript.

every()

The every() method is used to check if all elements in an array pass a certain test. It returns true if all elements pass, otherwise false:

const numbers = [10, 99, 75, 45, 33];

// check if all elements are > 15
const result = numbers.every(num => num > 15);

console.log(result); // false

The every() method executes a function once for each element present in the array. If it finds an array element for whom the function returns false, every() returns false and doesn't check the remaining elements.

some()

The some() method is similar to every() except that it returns true if one or more elements pass a certain condition:

const numbers = [10, 99, 75, 45, 33];

// check if any element > 15
const result = numbers.some(num => num > 15);

console.log(result); // true

includes()

The includes() method checks if the given element exists in the array. It is similar to the some() method. But instead of waiting for the specific condition to pass, it simply checks if the array contains the given element:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

fruits.includes('Apple'); // true
fruits.includes('Watermelon'); // false

Conclusion

That's all folks! In this article, we looked at JavaScript arrays in detail. We learned how to create an array, how to access an element from an array, how to add, update and remove elements, and so on.

In the end, we looked at some of the most commonly used array methods. There are many more methods that you can use to manipulate an array. Check out this MDN article to learn more about them.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: