Search code examples
javascriptarraysmethodscallbackarrow-functions

JavaScript Callback Confusing Behavior


Having trouble writing a callback function in JavaScript that returns a mapped array with each number in it incremented by one.

arr = [1, 2, 3, 4];

    const each = (elements, cb) => {
      for (let i = 0; i < elements.length; i++) {
        cb(elements[i], i);
      }
    };
    
    const map = (elements, cb) => {
      const mappedArr = [];
      each(elements, item => {
        mappedArr.push(cb(item));
      });
      return mappedArr;
    };



    const cb = (e) => {
      e += 1;
    }


    const newArr = map(arr, cb);
    console.log(newArr) // [ undefined, undefined, undefined, undefined ]

Your patience is appreciated in advance; I'm still learning and trying to understand callbacks. Please help me understand what I did wrong here.


Solution

  • Your cb is not returning anything at the moment, so the return value defaults to undefined. Use an arrow function with implicit return (no { }s) instead, so that the incremented value is returned.

    Also, try to avoid implicitly creating global variables (with your arr):

    const arr = [1, 2, 3, 4];
    
    const each = (elements, cb) => {
      for (let i = 0; i < elements.length; i++) {
        cb(elements[i], i);
      }
    };
    
    const map = (elements, cb) => {
      const mappedArr = [];
      each(elements, item => {
        mappedArr.push(cb(item));
      });
      return mappedArr;
    };
    
    const cb = e => e + 1;
    
    const newArr = map(arr, cb);
    console.log(newArr)