DEV Community

Abimanyu P
Abimanyu P

Posted on

Arrays in JavaScript

Arrays and its methods in JavaScript

An array in JavaScript is a data structure used to store multiple values in a single variable. we can store different data types and even can store a functions and objects in an array. It is useful when we have a collection of related data that needs to be stored and accessed together.

let fruits = ["Apple", "Banana", "Mango", "Orange"];
Enter fullscreen mode Exit fullscreen mode

In this example, fruits is an array containing four values. Every element in an array has an index, and indexing starts from 0. Therefore, Apple is at index 0, Banana is at index 1, and so on.

console.log(fruits[0]); // Apple
console.log(fruits[2]); // Mango
Enter fullscreen mode Exit fullscreen mode

We can also change an element by accessing its index.

fruits[1] = "Grapes";

console.log(fruits);
// ["Apple", "Grapes", "Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

The length property is used to find the number of elements in an array.

console.log(fruits.length);
// 4
Enter fullscreen mode Exit fullscreen mode

forEach()

forEach() is used to execute a function once for every element in an array. It is useful when we want to perform an action on each element without creating a new array.

let numbers = [10, 20, 30];

numbers.forEach(function(number) {
    console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

The function passed to forEach() runs three times because the array contains three elements. During each execution, number contains the current element.

10
20
30
Enter fullscreen mode Exit fullscreen mode

We can also get the index of the current element by adding a second parameter to the function.

numbers.forEach(function(number, index) {
    console.log(index, number);
});
Enter fullscreen mode Exit fullscreen mode

Output:

0 10
1 20
2 30
Enter fullscreen mode Exit fullscreen mode

The first parameter represents the current value and the second parameter represents its index.

map()

map() is used when we want to transform every element of an array and create a new array from the results.

For example, suppose we have an array of numbers and want to double every number.

let numbers = [10, 20, 30];

let doubled = numbers.map(function(number) {
    return number * 2;
});

console.log(doubled);
// [20, 40, 60]
Enter fullscreen mode Exit fullscreen mode

The function is executed for every element. For 10, it returns 20; for 20, it returns 40; and for 30, it returns 60. Those returned values are collected into a new array.

The original array is not changed:

console.log(numbers);
// [10, 20, 30]
Enter fullscreen mode Exit fullscreen mode

This is the main idea behind map():

Original array → transform each element → new array
Enter fullscreen mode Exit fullscreen mode

filter()

filter() is used to create a new array containing only the elements that satisfy a particular condition.

For example, suppose we want to get only the numbers greater than 20.

let numbers = [10, 15, 20, 25, 30];

let result = numbers.filter(function(number) {
    return number > 20;
});

console.log(result);
// [25, 30]
Enter fullscreen mode Exit fullscreen mode

The function is executed for every element. If the condition returns true, that element is added to the new array. If it returns false, the element is ignored.

For example, 10 > 20 is false, so 10 is not included. 25 > 20 is true, so 25 is included.

Like map(), filter() creates a new array and does not modify the original array.

find()

find() is used to find the first element that satisfies a condition.

let numbers = [10, 15, 20, 25, 30];

let result = numbers.find(function(number) {
    return number > 20;
});

console.log(result);
// 25
Enter fullscreen mode Exit fullscreen mode

Here, JavaScript checks the elements one by one. 10 and 15 do not satisfy the condition, and 20 is also not greater than 20. When it reaches 25, the condition becomes true, so find() returns 25 and stops searching.

Even though 30 also satisfies the condition, it is not returned because find() returns only the first matching element.

If no element matches the condition, find() returns undefined.

push() and pop()

push() and pop() are commonly used when adding or removing elements from the end of an array.

push() adds one or more elements to the end.

let fruits = ["Apple", "Banana"];

fruits.push("Mango");

console.log(fruits);
// ["Apple", "Banana", "Mango"]
Enter fullscreen mode Exit fullscreen mode

Here, "Mango" is added after "Banana". push() modifies the original array.

pop() does the opposite. It removes the last element.

let removedFruit = fruits.pop();

console.log(removedFruit);
// Mango

console.log(fruits);
// ["Apple", "Banana"]
Enter fullscreen mode Exit fullscreen mode

An important point is that pop() returns the element that it removed. This can be useful when we need to store or use the removed value.

push() → adds to the end
pop()  → removes from the end
Enter fullscreen mode Exit fullscreen mode

Similarly, unshift() adds an element at the beginning and shift() removes the first element.


fruits.unshift("Orange");
// ["Orange", "Apple", "Banana"]

fruits.shift();
// ["Apple", "Banana"]
Enter fullscreen mode Exit fullscreen mode

slice()

slice() is used to get a portion of an array. It returns a new array and does not modify the original array.

let fruits = ["Apple", "Banana", "Mango", "Orange"];

let result = fruits.slice(1, 3);

console.log(result);
// ["Banana", "Mango"]

console.log(fruits);
// ["Apple", "Banana", "Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

The first argument is the starting index, while the second argument is the ending index. The starting index is included, but the ending index is not.

So slice(1, 3) takes the elements at indexes 1 and 2.

Index:  0        1         2         3
       Apple    Banana    Mango     Orange
                 ↑---------↑
                 1         3
Enter fullscreen mode Exit fullscreen mode

This is why the result contains "Banana" and "Mango" but not "Orange".

splice()

splice() is used to add, remove, or replace elements in an array. Unlike slice(), it modifies the original array.

For example, we can remove elements using splice().

let fruits = ["Apple", "Banana", "Mango", "Orange"];

fruits.splice(1, 2);

console.log(fruits);
// ["Apple", "Orange"]
Enter fullscreen mode Exit fullscreen mode

The first argument, 1, tells JavaScript where to start. The second argument, 2, tells it how many elements to remove.

Therefore, starting from index 1, JavaScript removes two elements: "Banana" and "Mango".

We can also use splice() to add elements.

let fruits = ["Apple", "Banana", "Orange"];

fruits.splice(2, 0, "Mango");

console.log(fruits);
// ["Apple", "Banana", "Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

Here, 2 is the starting position, 0 means that no elements should be removed, and "Mango" is the element we want to add.

The important difference between slice() and splice() is:

slice()  → gets/copies a portion without changing the original
splice() → adds/removes elements and changes the original
Enter fullscreen mode Exit fullscreen mode

reduce()

reduce() is used when we want to process all the elements of an array and produce one final value.

For example, we can use it to calculate the total of numbers.

let numbers = [10, 20, 30, 40];

let total = numbers.reduce(function(sum, number) {
    return sum + number;
}, 0);

console.log(total);
// 100
Enter fullscreen mode Exit fullscreen mode

Here, sum stores the accumulated result, while number represents the current element. The 0 at the end is the initial value of sum.

The calculation happens like this:

0 + 10 = 10
10 + 20 = 30
30 + 30 = 60
60 + 40 = 100
Enter fullscreen mode Exit fullscreen mode

Finally, reduce() returns 100.

So while map() generally produces a new array and filter() produces a smaller array, reduce() is commonly used when we want to combine the elements into a single result.

Important Array Methods

Method Purpose
forEach() Performs an action for each element
map() Transforms elements and creates a new array
filter() Creates a new array with matching elements
find() Returns the first matching element
push() Adds elements to the end
pop() Removes the last element
slice() Copies a portion of an array
splice() Adds or removes elements
reduce() Combines elements into a single result

Top comments (0)