Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Updated
6 min read
Array Methods You Must Know

In the previous blog [JS Array](http:// https://karan2op.hashnode.dev/javascript-arrays) we have studied about arrays in js and in this blog we are gonna learn about the some important methods of array . The array have some inbuilt methods which are frequently used like pop, push , map ,filter which makes our life easy to perform operation with array.

pop and push:

Pop and push method insert or remove elements from the end of the array.

Push:

It insert any element at the end of the array , we don't need to care about what's the last index.

const fruits=["apple","mango","bannana"]
fruits.push("litchi")
console.log(fruits)

Output:

["apple","mango","bannana","litchi"]

pop:

It removes the last element of an array we don't need to pass the last index . It return's the removed element.

const fruits=["apple","mango","bannana"]
const removedElement=fruits.pop()
console.log("the removed element is ",removedElement)
console.log("the fruits array after removing the last element ",fruits)

Output:

the removed element is bannana
the fruits array after removing the last element ["apple","mango"]

shift and unshift:

shift:

shift method in arrays is used to remove the element from the beginning of the array and returns the removed element.

const fruits=["apple","mango","bannana"]
const removedElement=fruits.shift()
console.log("the removed element is ",removedElement)
console.log("the fruits array after removing the first element ",fruits)

Output:

the removed element is apple
the fruits array after removing the first element ["mango","bannana"]

unshift:

unshift method in arrays is used to insert the element at the beginning of the array .

const fruits=["apple","mango","bannana"]
fruits.unshift("litchi")
console.log(fruits)

Output:

["litchi","apple","mango","bannana"]

map method:

The map method is used when we want to perform the operation on every element of the array . Suppose you want to add the value 5 to every element of the array using map it is very easy to perform this. It return new array as a result and does not modify the original array . map method runs a callback function for every element of the array.

syntax:

array.map(callback(element, index, array), thisArg)

Parameters

  • element → current element being processed

  • index (optional) → index of the element

  • array (optional) → the array map() was called on

  • thisArg is the value that will be used as this inside the callback function.

const numbers=[5,6,7,8,9]
const result=numbers.map(function(num){
  return num+5
})
console.log(result)

Output:

[10,11,12,13,14]

let understand the last parameter thisArg in the map method.

thisArg:

It is the value that will be used as this inside the callback function.

Syntax:

array.map(callback, thisArg)

So when the callback runs, this will refer to the object passed as thisArg.

Example:

const obj = {
  multiplier: 2
};

const arr = [1, 2, 3];

const result = arr.map(function(num) {
  return num * this.multiplier;
}, obj);

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

here the value of multiplier is coming from the object passed as last parameter in map method.

filter :

As the name suggests, filter is used to filter out values from an array. The filter() method takes a callback function, and the callback returns a boolean value. If the returned value is true, the element is included in the result; if it is false, the element is excluded. The filter() method returns a new array containing the filtered elements.

Syntax:

array.filter(callback(element, index, array))

What it does

  • The callback must return true or false.

  • If it returns true → element is kept.

  • If it returns false → element is removed.

  • It returns a new array.

lets take a example where we just have to filter out all the values which are greater than 3 .

Example:

let arr = [1,2,3,4,5];

let result = arr.filter((num) => {
  return num > 3;
});

console.log(result); // [4,5]

reduce:

The reduce method reduce an array into a single value (like a sum, product, object, etc.). reduce() executes a callback on each array element and reduces the array to a single value. It returns the final accumulated result.

Syntax:

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

Parameters

  • accumulator → stores the result from previous iterations

  • currentValue → current element being processed

  • initialValue → starting value of the accumulator (optional but recommended)

Example Sum of array:

let arr = [1, 2, 3, 4];

let sum = arr.reduce((acc, curr) => {
  return acc + curr;
}, 0);

console.log(sum); // 10

Explanation:

  • Start with acc = 0

  • 0 + 1 = 1

  • 1 + 2 = 3

  • 3 + 3 = 6

  • 6 + 4 = 10

Final result → 10

forEach method:

forEach() is used to iterate over each element of an array and perform some operation. The forEach method takes a callback function and execute that function for the whole array. The forEach mutates the original array .

Syntax:

array.forEach(callback(element, index, array))

Parameters

  • element → current element being processed

  • index (optional) → index of the element

  • array (optional) → the array being traversed

Example:

let arr = [1, 2, 3];

arr.forEach((num) => {
  console.log(num);
});

//Output 
1
2
3

forEach vs map in JavaScript

Feature forEach() map()
Purpose Execute a function for each element Transform elements and create a new array
Return value undefined Returns a new array
Modifies original array No No
Use case Side effects (logging, API calls, updates) Data transformation
Async behavior ❌ Does not wait for promises ✅ Works with promises using Promise.all()

Async Problem with forEach():

const arr = [1,2,3];

arr.forEach(async (num) => {
  await new Promise(r => setTimeout(r,1000));
  console.log(num);
});

console.log("Done");

Output:

// Output 
Done
1
2
3

forEach() does not wait for promises.

The loop finishes immediately and "Done" prints first.

Async Handling with map():

const arr = [1,2,3];

const promises = arr.map(async (num) => {
  await new Promise(r => setTimeout(r,1000));
  return num * 2;
});

Promise.all(promises).then(result => {
  console.log(result);
});

Output:

[2,4,6]
  1. map() returns an array of promises

  2. Promise.all() waits for all promises to finish

So async operations work properly with map().

Conclusion:

JavaScript array methods make working with arrays much easier and more efficient. Methods like forEach(), map(), filter(), and reduce() help developers perform common operations such as iterating, transforming, filtering, and aggregating data in a clean and readable way. Understanding how and when to use these methods can greatly improve code quality and productivity. By mastering these array methods, developers can write more concise, expressive, and maintainable JavaScript code.

12 views