0
const arr = [36,19,69,27];

function push_to_array(data, cb){
  for(let i=0; i < data.length; i++){
      cb(data[i]);
  }
}

let test = push_to_array(arr, function(item){
    console.log(item);
    return item
});
console.log(test)

I apologize in advance for any lack in knowledge, I'm trying to wrap my head around Callbacks and Higher order Functions.

I'm attempting to loop in my callback function and return each value in the array. Right now the console.log(item) is showing that I'm indeed getting each value, but the return is saying that I am getting undefined. I'm not quite sure why and was just wondering what I'm doing wrong.

Thank you.

Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26
Mr.Mikey
  • 63
  • 5

2 Answers2

0

Your (oddly named) push_to_array should use the return value of cb if you want it to be visible later - did you want to create a new array depending on what gets returned for each item? If so, push_to_array should create an array and push the result of each cb to it:

function push_to_array(data, cb){
  const newArr = [];
  for(let i=0; i < data.length; i++){
      newArr.push(cb(data[i]));
  }
  return newArr;
}

let test = push_to_array([36,19,69,27], function(item){
    console.log(item);
    return item
});
console.log(test)

Or, using .map instead:

const push_to_array = (data, cb) => data.map(cb);

let test = push_to_array([36,19,69,27], function(item){
    console.log(item);
    return item
});
console.log(test)

That's assuming you want to construct a new array. If you want push_to_array to return the original array, rather than create a new one, then just return data at the end, instead of pushing to newArr.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

push_to_array is a void function. Meaning, it doesn't return anything. Hence, you're getting undefined.

I'm not sure what you wanted to return, but make sure you do it in push_to_array

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116