linkedin Skip to Main Content
Just announced: We now support interviewing in spreadsheets!
Back to blog

A Thorough Guide To JavaScript Array Methods with Examples

Development

The array data type is one of JavaScript’s most important data types because it stores different elements (with different data types) in a single variable. For example, when dealing with large amounts of data such as the JSON fake posts API, you frequently need to include a variety of data types such as objects, strings, integers, and many others. These values are typically stored in an array for manipulation and consumption in your application.

Working with arrays can be challenging for a beginner, especially when you want to perform functions like adding and removing specific data, looping through all the data in an array, sorting the data, and so on.

In this article, you will learn:

  • What is an array in JavaScript
  • How to create an array in JavaScript
  • How to remove items from an array
  • How to sort an array
  • How to add items to an array
  • How to iterate through an array

You will also learn how to use many methods to work with arrays, alongside an example of how each method works. These methods are essential as they offer you more flexibility than building your own custom logic from scratch. Not to mention, they are much easier and faster. 

✅ You can use the CoderPad sandbox at the bottom of this page or as a new browser window to run the code in this tutorial.

What is an array in JavaScript?

An array is a JavaScript data type that you can use to store multiple values in a single variable. This can be preferable to giving each value its own variable, even if they are all the same type of data. For example, if you have a list of cars, it is preferable to use an array rather than assigning a variable to each car.

// Using an array
let cars = ["Toyota", "Bugati", "Benz"];

// using individual variable
let car1 = "Toyota";
let car2 = "Bugati";
let car3 = "Benz";Code language: JavaScript (javascript)

Arrays make your code cleaner and more organized. You can use index numbers to retrieve array values. JavaScript’s arrays are zero-indexed, meaning the first element has an index of 0, the second has an index of 1, and so on, depending on how many elements are in the array.

Given the array of cars mentioned above, “Toyota” has an “index” of 0, while “Benz” has an “index” of 2. The order the values are positioned in is  called an “index” while the values themselves are called “elements”.

An array can store data of various types such as strings, integers, objects, boolean, and many others.

let values = [true, 12, "John Doe", {hobby: "reading"}];Code language: JavaScript (javascript)

How to create an array in JavaScript

You can create an array in two ways: using the Array constructor or using array literal notation. In practice, developers rarely use the Array constructor, so instead let’s focus on array literal notation, which uses square brackets [] to wrap a list of elements separated by commas.

// Using Array constructor
let names = new Array("John Doe", "Jane Doe", "Ann Doe");

// Using array literal notation
let names = ["John Doe", "Jane Doe", "Ann Doe"];Code language: JavaScript (javascript)

What about empty elements?

The term “empty element” can have different meanings in different scenarios, but in this context, an empty element means “no element”. For example, if you declare an array of name and then fail to attach an element before a comma:

let name = ["John", , "Jane", , "Ann"];Code language: JavaScript (javascript)

In other situations, empty elements could refer to null and undefined values. However, the methods in this guide will not execute functions for elements that are empty (has no value). We’ll remind you by noting “This method does not execute the function for empty elements” with the applicable code snippets.  

Now that you understand what an array is, how to make one, and how to access each element in an array, let’s look at how to manipulate them using the various built-in JavaScript array methods.

Destructive array methods

Destructive array methods alter the original arrays and return a modified array. Let’s look at the various methods for manipulating arrays that change the original array.

Methods to add to or remove from an array

It’s a fairly common occurrence to need to add or remove an element from an array. For example, take this array of names:

let names = ["John Doe", "Jane Doe", "Ann Doe"];Code language: JavaScript (javascript)

You can manipulate this array by using one of the below methods to add or remove either the first, last, or a specific element from the array.

pop()

This method is used to remove the last element of the attached JavaScript array. It changes the original array and returns the removed element.

// Syntax
myArray.pop()Code language: JavaScript (javascript)

Note: You don’t pass anything as a parameter into the pop() method.

Here is an example showing how to use the pop() method:

let names = ["John Doe", "Jane Doe", "Ann Doe"];
names.pop(); // "Ann Doe"
console.log(names); // ['John Doe', 'Jane Doe']Code language: JavaScript (javascript)

push()

This method is used to add new element(s) to the end of the attached JavaScript array. It changes the original array and returns the new length of the array. This method accepts the elements you wish to add at the end of the array as parameters.

// Syntax
myArray.push(element1, element2, ..., elementX)Code language: JavaScript (javascript)

Let’s now create a new array of scores and then add more scores to the array using the push method:

let scores = [12, 55, 78, 95, 33];
scores.push(66, 77); // 7

console.log(scores); // [12, 55, 78, 95, 33, 66, 77]Code language: JavaScript (javascript)

shift()

The shift() method removes the first element of an array. It works similarly to the pop() method, but instead of removing from the end, it now removes from the beginning of the attached array. It returns the removed/shifted element.

// Syntax
myArray.shift()Code language: JavaScript (javascript)

Note: You don’t pass anything as a parameter into the shift() method.

Let’s now create a new array of animal names and then learn how to use the shift method to remove the first name from the array:

let animalNames = ["Lion", "Dog", "Snake", "Tiger"];
animalNames.shift(); // "Lion"

console.log(animalNames); // ['Dog', 'Snake', 'Tiger']Code language: JavaScript (javascript)

unshift()

The unshift() method works very similarly to the push() method as it is also used to add new elements to an array, but to the beginning of an array. This method takes in the element(s) you wish to add at the beginning of the array as parameters. It also returns the new length of the array.

// Syntax
myArray.unshift(element1, element2, ..., elementX)Code language: JavaScript (javascript)

Let’s now create a new array of food names and then add more food names to the array using the unshift() method:

let foodNames = ["Salad", "Bread", "Fish", "Rice"];
foodNames.unshift("Pizza", "Cake"); // Returns 6 - the length of the newly changed array
console.log(foodNames); // ['Pizza', 'Cake', 'Salad', 'Bread', 'Fish', 'Rice']Code language: JavaScript (javascript)

splice()

The splice() method adds or removes a specific element (or elements) from an array. When removing elements, it returns the removed element(s) in an array, and when you add elements, it returns an empty array.

// Syntax
myArray.splice(index, howMany, element1, element2, ..., elementX)Code language: JavaScript (javascript)

In the above syntax, index is a required parameter as it stands for the position where you want to add or remove elements. howMany is an optional parameter. It stands for the number of elements to be removed. Any other parameter is optional, and will be the new element(s) you want to add to the specified position.

Suppose you have an array of fruits:

let fruits = ["Mango", "Strawberries", "Lime", "Oranges", "Pomegranate"];Code language: JavaScript (javascript)

You can make use of the splice method to remove specific elements such as the third fruit, the first and second fruits, and lots more:

// Remove third fruit
fruits.splice(2,1); // ['Lime']
console.log(fruits); // ["Mango", "Strawberries", "Oranges", "Pomegranate"]

// Remove the first and second fruits
fruits.splice(0,2); // ['Mango', 'Strawberries']
console.log(fruits); // ["Oranges", "Pomegranate"]Code language: JavaScript (javascript)

✅ Remember, arrays start counting at 0. This means that arr[2] is the third item in the array.

You can also decide to add specific fruits to specific positions within your array using the splice method:

// Add to the first position without removing any elements
fruits.splice(0, 0, "Grape"); // []
console.log(fruits); // ['Grape', 'Mango', 'Strawberries', 'Lime', 'Oranges', 'Pomegranate']

// Add to the fifth and sixth position by replacing them with new fruits
fruits.splice(4, 2, "Bananas", "Avocado"); // ['Oranges', 'Pomegranate']
console.log(fruits); // ['Grape', 'Mango', 'Strawberries', 'Lime', 'Bananas', 'Avocado']Code language: JavaScript (javascript)

The splice method is one of the most flexible tools for adding and removing elements from your arrays. 

Sort or Reverse an Array

The sort() and reverse() JavaScript array methods, as their names imply, change the order of elements in your data.

sort()

The sort method is used to sort an array of elements alphabetically (from A-Z) and returns the sorted array.

// Syntax
myArray.sort();Code language: JavaScript (javascript)

Suppose you have an array of fruits that you want to sort so that they are arranged alphabetically:

let fruits = ["Mango", "Strawberries", "Lime", "Oranges"];
fruits.sort(); // ['Lime', 'Mango', 'Oranges', 'Strawberries']

console.log(fruits); // ['Lime', 'Mango', 'Oranges', 'Strawberries']Code language: JavaScript (javascript)

By default, uppercase letters are sorted before lowercase letters, meaning “Apple”, “Strawberries”, and “Lime” will come before “apple”:

let fruits = ["Apple", "Strawberries", "apple", "Lime"];
fruits.sort(); // ['Apple', 'Lime', 'Strawberries', 'apple']

console.log(fruits); // ['Apple', 'Lime', 'Strawberries', 'apple']Code language: JavaScript (javascript)

You can also use this method to sort numbers by providing a comparison function in the sort method. By default, the sort() method sorts values as strings. If numbers are sorted as strings, “75” is bigger than “200” because “7” is bigger than “2”.

let numbers = [75, 200];
numbers.sort(); // [200, 75]Code language: JavaScript (javascript)

You can make use of a comparison function to help sort numeric values:

let numbers = [75, 200];
numbers.sort(function(a, b){return a - b}); // [75, 200]Code language: JavaScript (javascript)

reverse()

The reverse() method changes the original array and returns an array of reversed elements. This method does not take in any parameters.

// Syntax
myArray.reverse()Code language: JavaScript (javascript)

Here, we use the reverse method to flip the arrangement of an array of letters. 

let letters = ['c', 'o', 'd', 'e', 'r', 'p', 'a', 'd'];
letters.reverse(); // ['d', 'a', 'p', 'r', 'e', 'd', 'o', 'c']

console.log(letters); // ['d', 'a', 'p', 'r', 'e', 'd', 'o', 'c']Code language: JavaScript (javascript)

Non-Destructive Array methods

A non-destructive array method returns a new or non-modified array even after using an array method. If you want to preserve the original array while assigning the new output to a new array, you can use these non-destructive array methods.

Methods to add to or remove elements from an array

You know how to add or remove an element from an array with destructive methods–now let’s explore the non-destructive side.

concat()

Suppose you have two or more arrays that you want to join together. You can use the concat() method. This method joins the arrays or adds an element to an array and then returns a new array containing the joined arrays or new element(s).

// Syntax
myArray1.concat(myArray2, myArray3, ..., myArrayX)Code language: JavaScript (javascript)

Or

array1.concat(element1, ..., elementX)Code language: CSS (css)

Suppose you have two arrays of European and African country names:

let EuroCountries = ["Germany", "Poland", "Sweden"];
let AfricanCountries = ["Ghana", "Nigeria"];Code language: JavaScript (javascript)

You can then combine these arrays with the concat() method and assign the new array to a new variable, thereby leaving our original arrays still intact:

let countries = EuroCountries.concat(AfricanCountries);

console.log(countries); // ['Germany', 'Poland', 'Sweden', 'Ghana', 'Nigeria']Code language: JavaScript (javascript)

You can also add only elements, or you can add arrays and elements as seen below:

let countries = EuroCountries.concat("Togo", "Rwanda");
console.log(countries); // ['Germany', 'Poland', 'Sweden', 'Togo', 'Rwanda']

let countries = EuroCountries.concat(AfricanCountries, "South Africa");
console.log(countries); // ['Germany', 'Poland', 'Sweden', 'Ghana', 'Nigeria', 'South Africa']Code language: JavaScript (javascript)

slice()

The slice() method takes the specified element(s) from one array into a new one without changing the original. This method takes two optional parameters: the start and end positions. By default, the start is 0, while the end is your array’s last element. 

// Syntax
myArray.slice(start, end)Code language: JavaScript (javascript)

The start position indicates the index position of the first element, while the end position is the last position that is not included among the copied elements.

In this array of countries, we use the slice method to copy elements into new arrays: 

let countries = ['Germany', 'Poland', 'Sweden', 'Ghana', 'Nigeria', 'South Africa'];

let euroCountries = countries.slice(0, 3);
console.log(euroCountries); // ['Germany', 'Poland', 'Sweden']

let africanCountries = countries.slice(3);
console.log(africanCountries); // ['Ghana', 'Nigeria', 'South Africa']Code language: JavaScript (javascript)

Join an Array

Let’s say you need to join all the array elements to become a string. You can do this with the join() method without altering or changing the original array.

join()

The join() method returns an array as a string. This method takes in your preferred separator as its parameter.

// Syntax
myArray.join(separator)Code language: JavaScript (javascript)

The separator parameter is optional – if you don’t put anything in, it will default to using a comma. But, as you can see in our example, it does accept other symbols and spaces to separate each element in your array when converting it to a string:

let names = ['John', 'Doe'];
let joinedNames1 = names.join(); // 'John,Doe'
let joinedNames2 = names.join(' '); // 'John Doe'
let joinedNames3 = names.join('-'); // 'John-Doe'Code language: JavaScript (javascript)

Iterating over array elements

Traditionally, you had to use loops to iterate through an array if you wanted to do any kind of data checks or processing on the individual elements. 

For example if you had an array of students where you wanted to display a particular student on a website, you’d have to loop through the entire array and then create your own logic to filter them based on your filter criteria.

Handling all this from scratch can be very complex, but JavaScript already has some built-in methods you can use to perform all these tasks efficiently. Here is an overview of the most common methods for iterating over your arrays. 

includes()

As the term suggests, the includes() method checks through an array to see if the array contains a specified value. If it contains that value, it returns true – if not, it will return false. The method accepts two parameters: the specific value, and the optional start position.

// Syntax
myArray.includes(value, start)Code language: JavaScript (javascript)

By default, the start is 0, meaning it searches through all the array elements. Also, this method is case-sensitive, meaning “Hello” is not the same as “hello”.

Suppose you have an array of fruits. Let’s check if the array includes “Apple”:

let fruits = ["Apple", "Strawberries", "Mango", "Lime", "Oranges"];

console.log(fruits.includes("Apple")); // true
console.log(fruits.includes("Apple", 3)); // falseCode language: JavaScript (javascript)

every()

The every() method executes a function for each element of an array in the form of an evaluation. It returns true if all the array elements pass the evaluation and returns false (and stops execution) if at least one element fails the evaluation. This method uses a callback function as an argument which is evaluated for each element.

// Syntax
myArray.every(callbackFn)Code language: JavaScript (javascript)

In the callback function, you have access to each element, the index, and the original array itself:

// Normal function
myArray.every(function(element, index, array){ /* ... */ })

// Arrow function
myArray.every((element, index, array) => { /* ... */ })Code language: JavaScript (javascript)

Suppose you have an array of users’ ages, and you want to check if all the users are below 50 years old:

let usersAge = [22, 56, 75, 33, 22, 80, 12, 43, 23];

console.log(usersAge.every((age) => age < 50)); // falseCode language: JavaScript (javascript)

You can also decide to create the function and then pass it in:

let usersAge = [22, 56, 75, 33, 22, 80, 12, 43, 23];

function checkAge(age) {
    return age < 50;
}

console.log(usersAge.every(checkAge)); // falseCode language: JavaScript (javascript)

Note: This method does not execute the function for empty elements.

some()

The .some() method is very similar to the every() method, but this time returns true and stops execution if it passes the evaluation for one of the array elements. It will return false if all the elements fail the evaluation.

// Syntax
myArray.some(callbackFn)Code language: JavaScript (javascript)

In the callback function, you have access to each element, the index, and the original array itself:

// Normal function
myArray.some(function(element, index, array){ /* ... */ })

// Arrow function
myArray.some((element, index, array) => { /* ... */ })Code language: JavaScript (javascript)

In our array of users’ ages, suppose you want to check if at least one is above 50 years:

let usersAge = [22, 56, 75, 33, 22, 80, 12, 43, 23];

console.log(usersAge.some((age) => age > 50)); // trueCode language: JavaScript (javascript)

Note: This method does not execute the function for empty elements.

find()

The find method is also similar to the some() method but doesn’t return a boolean—it will instead return the first element that passes a test. Like the some() and every() method, it also executes the callback function for every element and will return undefined if no element passes the test. Its syntax is also similar to both methods.

// Syntax
myArray.find(callbackFn)Code language: JavaScript (javascript)

In the callback function, you have access to each element, the index, and the original array itself:

// Normal function
myArray.find(function(element, index, array){ /* ... */ })

// Arrow function
myArray.find((element, index, array) => { /* ... */ })Code language: JavaScript (javascript)

Suppose you have an array of students, with each student having an object that contains their name and age. You can find a student with a particular name and output the student’s age:

let students = [
    { name: "John Doe", age: 22 },
    { name: "Jane Doe", age: 33 },
    { name: "Karl Don", age: 21 }
];

console.log(students.find((student) => student.name === "John Doe").age); // 22Code language: JavaScript (javascript)

You can decide to extract the function:

let students = [
    { name: "John Doe", age: 22 },
    { name: "Jane Doe", age: 33 },
    { name: "Karl Don", age: 21 }
];

const checkStudents = (student) => {
    if (student.name === "John Doe") {
    return student;
    }
};

console.log(students.find(checkStudents).age); // 22Code language: JavaScript (javascript)

Note: This method does not execute the function for empty elements.

findIndex()

This method is very similar to the find() method, but this time, instead of returning the element, it returns the index (position) of the first element in the array that passes the test function. It will return -1 if nothing matches. Its syntax is similar to the find() method.

// Syntax
myArray.findIndex(callbackFn)Code language: JavaScript (javascript)

In the callback function, you have access to each element, the index, and the original array itself:

// Normal function
myArray.findIndex(function(element, index, array){ /* ... */ })

// Arrow function
myArray.findIndex((element, index, array) => { /* ... */ })Code language: JavaScript (javascript)

Suppose you have an array of students, each with an object containing their name and age. You can find a student with a particular name and output the index of that student:

let students = [
    { name: "John Doe", age: 22 },
    { name: "Jane Doe", age: 33 },
    { name: "Karl Don", age: 21 }
];

const checkStudents = (student) => {
    if (student.name === "Jane Doe") {
    return student
    }
};

console.log(students.findIndex(checkStudents)); // 1Code language: JavaScript (javascript)

You can also use one line with an arrow function:

let students = [
    { name: "John Doe", age: 22 },
    { name: "Jane Doe", age: 33 },
    { name: "Karl Don", age: 21 }
];

console.log(students.findIndex((student) => student.name === "Jane Doe")); // 1Code language: JavaScript (javascript)

Note: This method does not execute the function for empty elements.

indexOf()

This method checks through each element and returns the index of the first element that matches the specified value. The search is done using strict equality === and will return -1 if the specified value does not match any of the array’s element(s). 

The findIndex() method and this one are pretty similar, except the findIndex() method takes a callback function, while for indexOf(), you simultaneously pass the value you’re looking for directly.

// Syntax
myArray.indexOf(item)
myArray.indexOf(item, start)Code language: JavaScript (javascript)

The start parameter is optional, indicating the index (position) you want the search to begin. When you use a negative number, the search begins from the end of the array. By default, its value is 0.

 Here is an example to show how this method works:

let scores = [23, 56, 67, 22, 45, 57, 45, 7, 5, 34, 7];

console.log(scores.indexOf(7)); // 7
console.log(scores.indexOf(7, -1)); // 10Code language: JavaScript (javascript)

filter()

The filter() method goes over the entire array and looks for elements that meet a specified condition. It then returns all the elements that pass the condition in a new array. 

Suppose you have an array of users and want to filter them based on their age. When you use this method, it returns all elements that match the condition.

// Syntax
myArray.filter(callbackFn)Code language: JavaScript (javascript)

In the callback function, you have access to each element, the index, and the original array itself:

// Normal function
myArray.filter(function(element, index, array){ /* ... */ })

// Arrow function
myArray.filter((element, index, array) => { /* ... */ })Code language: JavaScript (javascript)

Using the array of students, you can check for students whose age is less than 30 and return them:

let students = [
    { name: "John Doe", age: 22 },
    { name: "Jane Doe", age: 33 },
    { name: "Karl Don", age: 21 }
];

console.log(students.filter((student) => student.age < 30));Code language: JavaScript (javascript)

This will output:

[
    { "name": "John Doe", "age": 22 },
    { "name": "Karl Don", "age": 21 }
]Code language: JSON / JSON with Comments (json)

Note: This method does not execute the function for empty elements.

forEach()

The forEach() method is used to loop through all elements of an array and calls a function (callback function) for each element in the array. The callback function has access to the current element, index, and the entire array on every loop.

// Syntax
myArray.forEach(callbackFn)
myArray.forEach(function(element, index, array){ /* ... */ })Code language: PHP (php)

Suppose you have an array of staff with their total salaries. You can add up all the salaries:

let staff = [
    { name: "John Doe", salary: 120 },
    { name: "Jane Doe", salary: 350 },
    { name: "Karl Don", salary: 710 }
];

let totalSalary = 0;

staff.forEach((staffPerson) => {
    totalSalary += staffPerson.salary;
});

console.log(totalSalary); // 1180Code language: JavaScript (javascript)

You can also use dot notation to access individual array objects as well as their values:

staff.forEach((staffPerson) => {
    let sentence = `${staffPerson.name} earns ${staffPerson.salary}`;
    console.log(sentence);
});Code language: JavaScript (javascript)

This will output:

"John Doe earns 120"
"Jane Doe earns 350"
"Karl Don earns 710"Code language: JSON / JSON with Comments (json)

Note: This method does not execute the function for empty elements.

map()

The map() method is used to iterate over an array and modify its elements using a callback function. This callback function will run on each array element and return a new array of modified elements.

// Syntax
myArray.map(callbackFn)
myArray.map(function(element, index, array){ /* ... */ })Code language: JavaScript (javascript)

Suppose you have an array of scores, and you want to add 5 points to each score and return a new array:

let scores = [45, 71, 65, 80, 47];

let newScores = scores.map((score) => score + 5);

console.log(newScores); // [50,76,70,85,52]Code language: JavaScript (javascript)

The map() and forEach() methods appear to be somewhat similar, but map() allows us to return a value, while forEach() does not. This means you should utilize the map() method whenever you want to return a value for each item in an array.

reduce()

This is one of the most powerful JavaScript array methods because it applies a reducer function to each element of your array and returns a single output. The reducer function iterates through all elements in your array from left to right (in order) and returns the result of the previous element’s calculation. 

Thus, the final result is a single value. This single value is the function’s accumulated result after executing a reducer function for every array element.

// Syntax
myArray.reduce(callbackFn, initialValue)Code language: JavaScript (javascript)

This method takes two primary parameters, the callback function and an optional parameter of initialValue (a value to be passed to the function as the initial value). The callback function itself is quite different from other methods as it has an additional total parameter, which is either the initalValue or the last returned value of the function.

myArray.reduce((total, currentValue, currentIndex, arr) => { /* ... */ }, initialValue)Code language: JavaScript (javascript)

Here is an example to show how this method works:

let staff = [
    { name: "John Doe", salary: 120 },
    { name: "Jane Doe", salary: 350 },
    { name: "Karl Don", salary: 710 }
];

const totalSalary = staff.reduce((total, staffPerson) => {
    total += staffPerson.salary;
    return total;
}, 0);

console.log(totalSalary); // 1180Code language: JavaScript (javascript)

ℹ️ Reduce is a complex array method. If you’d like to learn more about it, MDN has a more in-depth look at the method.

flat()

The flat() method creates a new array with all sub-array elements concatenated into the new array based on a specified depth. This method accepts an optional parameter known as depth.

// Syntax
myArray.flat()
myArray.flat(depth)Code language: JavaScript (javascript)

Here is an example of how this method works:

let numbers = [23, 56, 67, [22, 45, 57, [45, 7], 5], [34, 07]];

console.log(numbers.flat()); // [23, 56, 67, 22, 45, 57, [45, 7], 5, 34, 7]
console.log(numbers.flat(2)); // [23, 56, 67, 22, 45, 57, 45, 7, 5, 34, 7]Code language: JavaScript (javascript)

flatmap()

The flatmap() method is the result of combining the map() and flat() methods. It returns a new array created by applying a given callback function to each array element and then flattening the result by one level.

// Syntax
myArray.forEach(callbackFn)
myArray.forEach(function(element, index, array){ /* ... */ })Code language: PHP (php)

Here is an example to show how this method works:

let numbers = [23, 56, 67, 22, 45, 57, 45, 7, 5];

let doubleNumbers = numbers.flatMap((number) => number * 2);

console.log(doubleNumbers); // [46, 112, 134, 44, 90, 114, 90, 14, 10]Code language: JavaScript (javascript)

Try it out!

Wrapping up

This article has taught you all the built-in JavaScript methods, their functions, and how they work with examples. You can now explore these methods one by one to better understand how they work and in what situations you can use them. Try it out in the CoderPad sandbox. 

I’m Joel Olawanle, a frontend developer and technical writer interested in making the web accessible to everyone by always looking for ways to give back to the tech community. Follow me and connect with me on Twitter.