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

1 Answer

0 votes
// Using a custom callback function
// mimic the callback‑passing style from languages like C or Go:

// Custom function that applies a callback to each element
function applyToArray(arr, callback) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(callback(arr[i]));
  }
  return result;
}

// callback
function square(x) {
  return x * x;
}

const numbers = [2, 4, 6, 8];

const squared = applyToArray(numbers, square);

console.log(squared);



/*
run:

[ 4, 16, 36, 64 ]

*/

 



answered Mar 20 by avibootz

Related questions

...