DEV Community

A K I L A N
A K I L A N

Posted on

For each & map

array.Foreach()

  • The foreach() methods calls a function for each element in a array,it not executed for empty elements
const number = [33,44,55,66,77]
number.forEach(value);
function value(i,j,k){
    console.log(i,j,k);
}

Enter fullscreen mode Exit fullscreen mode

  • if we call foreach before declation in expresss & airrow function we get reference error.

  • the best practice is to use declaration function

  • this doen't return any values.if we return it will give undefined

  • the foreach will give values , indexnumber,and array this three values by default if we want those.

  • It's primarily used for executing side effects like logging to the console or modifying external variables.

array.map()

  • map() creates a new array from caliing function for every array element,dont execute the function for empty elements

  • does not change the orginial array

  • it returns values

  • same syntax as foreach

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Outputs: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode
  • It's perfect for data transformation without mutating the original array.

Top comments (0)