Search code examples
javascriptforeacharrow-functions

JavaScript forEach method not work with Arrow Function


const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
const function5 = (index, element) => {return index + ": " + element};
console.log(array3.forEach(function5));

Why this code not work, what I do wrong?


Solution

  • You need to use .map() as .forEach() will return you undefined always, and the result you expect can be obtained by using map() function:

    const array3 = [5, 10, 15, 20, 25, 30, 35, 40];
    const function5 = (index, element) => {return index + ": " + element};
    console.log(array3.map(function5));