DEV Community

R.Shobika CSE
R.Shobika CSE

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.

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. 
Enter fullscreen mode Exit fullscreen mode

Output:
this is a function
this is a function
this is a function
this is a function

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.
Enter fullscreen mode Exit fullscreen mode

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:

  • Synchronous Callbacks

  • Asynchronous Callbacks

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

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.


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);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)