JavaScript Array Methods – Complete Guide to Array Iterations
Arrays are one of the most powerful data structures in JavaScript. They allow us to store multiple values inside a single variable and manage data efficiently. But just storing data is not enough — we must process, search, and transform it.
That is where Array Methods and Iteration Methods play an important role.
These methods are widely used in modern development, especially in frameworks like React and backend environments like Node.js.
Below are some important array methods every JavaScript developer should know.
indexOf() – Find First Position
The indexOf() method returns the first index of a specified value in an array. If the value is not found, it returns -1.
Example:
let fruits = ["apple", "banana", "mango", "banana"];
console.log(fruits.indexOf("banana"));
Output: 1
It finds the first occurrence of the value.
It helps to check whether an element exists in an array.
lastIndexOf() – Find Last Position
The lastIndexOf() method returns the last index of a specified value in an array. If the value is not found, it returns -1.
Example:
let fruits = ["apple", "banana", "mango", "banana"];
console.log(fruits.lastIndexOf("banana"));
Output: 3
It is useful when duplicate values exist in an array.
It searches from the end of the array.
forEach() – Execute for Each Element
The forEach() method executes a function once for every element in the array.
Example:
let numbers = [1, 2, 3, 4];
numbers.forEach(function(num){
console.log(num);
});
It performs an action for each element.
It does not return a new array.
map() – Transform Array
The map() method creates a new array by applying a function to every element of the original array.
Example:
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(function(num){
return num * 2;
});
console.log(doubled);
Output: [2, 4, 6, 8]
It returns a new array.
It does not modify the original array.
It is mainly used for transforming data.
filter() – Filter Based on Condition
The filter() method creates a new array containing elements that satisfy a given condition.
Example:
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(function(num){
return num % 2 === 0;
});
console.log(even);
Output: [2, 4]
It returns only matching elements.
It is commonly used in real-world applications.
find() – Find First Matching Element
The find() method returns the first element in the array that satisfies a condition.
Example:
let numbers = [10, 20, 30, 40];
let result = numbers.find(function(num){
return num > 25;
});
console.log(result);
Output: 30
It stops searching after the first match.
It returns undefined if no element matches.
reduce() – Reduce to Single Value
The reduce() method reduces the array to a single value by applying a function to each element.
Example:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce(function(total, num){
return total + num;
}, 0);
console.log(sum);
Output: 10
Top comments (0)