How to apply a callback to an array (apply a function to each element) in JavaScript

3 Answers

0 votes
// Using Array.map() (returns a new array)

// Callback: takes a number and returns a new number
function double(x) {
  return x * 2;
}

const numbers = [5, 10, 15, 20];

// Apply the callback to each element
const doubled = numbers.map(double);

console.log(doubled); 



/*
run:

[ 10, 20, 30, 40 ]

*/

 



answered Mar 20 by avibootz
0 votes
// Using Array.forEach() (modifies in place or performs side effects)

const numbers = [5, 10, 15, 20];

// Callback: modifies each element in place
numbers.forEach((value, index, arr) => {
  arr[index] = value * 2;
});

console.log(numbers);



/*
run:

[ 10, 20, 30, 40 ]

*/

 



answered Mar 20 by avibootz
0 votes
// Using an inline arrow function as the callback

const numbers = [5, 10, 15, 20];

const tripled = numbers.map(x => x * 3);

console.log(tripled);


/*
run:

[ 15, 30, 45, 60 ]

*/

 



answered Mar 20 by avibootz
...