Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Updated
6 min readView as Markdown
Array Methods You Must Know

Introduction

Before deep dive into the Array method let's first understand what is an Array?

Array is a ordered collection of elements each separated by "," comma. array can store multiple values in a single variable.

In JavaScript Array is an special object with built-in methods for working with ordered data.

Using Array we can store multiple type of data whether it can be : String, Number, Object, Boolean or even Arrray itself.

Array is very powerful data structure but it is way more powerful with its methods, So ln this article we will understand about array methods


JavaScript has two types of Array methods

  • Mutating Methods

  • Non-Mutating Methods

Mutating Methods

Mutating methods modifiy the original array, let's cover each method

push() Method:

  • It adds element to the end of an array.

  • length automatically updates after value added.

  • It returns the new length of the array

let animes = ["Naruto", "One-piece", "Demon slayer", "Haikyuu"]

animes.push("Attack on titan")

console.log(animes)

// Output: ['Naruto', 'One-piece', 'Demon slayer', 'Haikyuu', 'Attack on titan']

It can push multiple elements all at once

let animes = ["Naruto", "Haikyuu"]

animes.push("Attack on titan", "One-piece")

console.log(animes)

// Output: [ 'Naruto', 'Haikyuu', 'Attack on titan', 'One-piece' ]

pop() Method:

  • Removes the last element from an array.

  • Returns the removed element.

  • Returns undefined if the array is empty

  • length automatically updates after value removed.

let animes = ["Naruto", "Haikyuu", "One-piece"]

animes.pop()

console.log(animes)

//Output : [ 'Naruto', 'Haikyuu' ]

shift() Method

  • Removes the first element from an array

  • Returns the removed element

  • Returns undefined if the array is empty

  • After first element removed remaining all elements's index will move one position left it's like "1" index will become "0"

let animes = ["Naruto", "Haikyuu", "One-piece"]

animes.shift()

console.log(animes)

// Output: [ 'Haikyuu', 'One-piece' ]

unshift() Method

  • It adds element to the beginning of an array.

  • Return new length of the array

  • After added to the beginning elements index position will move to the right, so basically all indexes changes.

let animes = ["Naruto", "Haikyuu", "One-piece"]

animes.unshift("Bleach")

console.log(animes)

// Output: [ 'Bleach', 'Naruto', 'Haikyuu', 'One-piece' ]

it can add multiple elements to the beginning all at once

let animes = ["Naruto", "Haikyuu", "One-piece"]

animes.unshift("Bleach", "Demon slayer")

console.log(animes)

// Output: [ 'Bleach', 'Demon slayer', 'Naruto', 'Haikyuu', 'One-piece' ]

Non-Mutating Methods

Non-mutating methods are those which return new Array instead of modifying the original. These methods are widely use in JavaScript.

Non-mutating methods are:

  • map()

  • filter()

  • reduce()

map() Method

map() method is very useful for creating new array from the original array, it can be used for data transformation, UI rendering (in react) or object manipulation.

map() access every element of array and execute call back function for each element. after function execution returned value will store in new Array.

callback function has mainly two parameter first is array element and second one is index value starting from 0

Here are some key points:

  • It iterates through every element of array

  • It does not mutate the original array

  • It returns a new array

const nums = [1, 2, 3, 4];

const doubled = nums.map(n => n * 2);

console.log(doubled); // [2, 4, 6, 8]

filter() method

In JavaScript filter is very useful method, as it's name suggest it used to filter array element and returns new array.

It is based on boolean values it means if condition is true it will return that element in new Array and if condition is false it will skip that element.

It also has call function which takes parameters first is array element and second is index.

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

const even = nums.filter(n => n % 2 === 0);

console.log(even); // [2,4]

reduce() method

reduce() is very powerful method in JavaScript is used for combine all elements of an array into a single value by applying a callback function to each element.

reduce method has 2 paramter one is callback function second is initial value, this initial assigned to the accumulator,

It can be use for calculating total price, sum or product of all numbers.

It also has call function which takes three parameter :

  1. Accumulator: Stores the result of every iteration

  2. CurrentValue: Current element which being processed.

  3. CurrentIndex: Index value of current element

const nums = [1,2,3,4];

const sum = nums.reduce((acc, n) => acc + n, 0);

console.log(sum); // 10

Here accumulator must have a initial value, reduce method can return result in any data type it can be array, number, string or object.

forEach() method

forEach() method is also one of the most useful array method, the only difference is that it does not return a new Array.

We can use it for modifying the original array based on condition.

It also has a call back function with mainly takes two paramter first is array element and second is index value.

const fruits = ["apple","banana","mango"];

fruits.forEach((fruit) => {
  console.log(fruit);
});

for loop vs map/filter

Feature for loop map filter
Purpose General iteration Transform each element Select based on condition
Return value Nothing by default New array New array
Array length depends on logic Same as original Can be smaller
Use Case For complex logic Transform data filtering data

Assignments

Task 1: Create a array of number using [] brackets like [1, 2, 3, 4].

Task 2: Now use map method to iterate through each element and perfom operation to double each number.

Task 3: Use filter() mathod to extract numbers greater than 10 (use conditional operators).

Task 4: Use reduce() method to calculate sum of all numbers.

Conclusion

JavaScript array methods play a very important role, and each method has its own advantages and use cases. Behind the scenes, most of these methods work similarly to simple loops, but using them directly saves a significant amount of time and effort.

Another important thing developers should understand is which array methods mutate the original array and which do not. Knowing this helps us write cleaner and safer code without causing unintended side effects.

Hope you like this article❤️