DEV Community

Keerthana M
Keerthana M

Posted on

ARRAY ITERATIONS IN JS.

1. Array forEach() :

  • This forEach method call a function in a each array element.
  • It doenot return any array.
  • It will give three arguments like values, index, array.

Example:

const num = [10,20,30,40];
const display=function(i){
console.log("this is a function",i);
}
num.forEach(display);
// this line will call the display function.

Output:
this is a function 10
this is a function 20
this is a function 30
this is a function 40

Example:
const num = [10,20,30,40];
const display = function(i,j,k){
console.log("this is a function",i,j,k);
}
num.forEach(display);
//this line will call the display function.

output:
this is a function 10 0 [ 10, 20, 30, 40 ]
this is a function 20 1 [ 10, 20, 30, 40 ]
this is a function 30 2 [ 10, 20, 30, 40 ]
this is a function 40 3 [ 10, 20, 30, 40 ]

This method give the value, index and array.

CallBack Function:

  • Callback function is a function is passed into a argument for the another function which is executed later to complete a specific task.
  • There are 2 type of callback function are:
  1. Synchronous Callbacks
  2. Asynchronous Callbacks

function home(click){
click();
}
function greet(){
console.log("welcome to the callback Function Tutor");
}
home(greet);

output:
welcome to the callback Function Tutor

Map:

  • This function is also similar to the forEach method but this method return the value.
  • It will create a new array does not disturb the original array.

Example:
const num = [10,20,30,40];
const display=function(i){
// console.log("this is a function",i);
return i*2;
}
console.log(num.map(display));
console.log(num);

output:
[ 20, 40, 60, 80 ]
[ 10, 20, 30, 40 ]

Example:

const numbers = [45,10,25,30,60];
function display (value, index, array ){
return value * 2;
}
const forEachReturn = numbers.forEach(display);
const MapReturn = numbers.map(display);
console.log(forEachReturn);
console.log(MapReturn)
console.log(numbers);

output:
undefined
[ 90, 20, 50, 60, 120 ]
[ 45, 10, 25, 30, 60 ]

example:
const numbers2 = [1, 2, 3];
const resultForEach = numbers2.forEach(num => num * 2);
console.log(resultForEach);
const resultMap = numbers2.map(num => num * 2);
console.log(resultMap);

output:
undefined
[ 2, 4, 6 ]

example:
const users = [
{ id: 1, name: "Sam" },
{ id: 2, name: "Alex" }
];
const usernames = users.map(user => user.name);
console.log(usernames);
const username = users.forEach(user => user.name);
console.log(username)

output:
Array [ "Sam", "Alex" ]
undefined

example:
const sparseArr = [1, , 3, , 5];
sparseArr.forEach(n => console.log(n));
const mapped = sparseArr.map(n => n * 2);
console.log(mapped);

output:
1
3
5
[ 2, <1 empty slot>, 6, <1 empty slot>, 10 ]

Difference between forEach() and map():

Top comments (0)