'Javascript forEach Method

Am getting undefined error.

var fruits = ["apple", "orange", "cherry"];
document.getElementById("demo").innerHTML = fruits.forEach(myFunction);

function myFunction(item, index) {
  return index + ":" + item + "<br>";
}


Solution 1:[1]

var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {
  document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
<p>List all array items, with keys and values:</p>

<p id="demo"></p>

Solution 2:[2]

Return value The return value of arr.forEach function is always undefined

So you can create a wrapper function which will use forEach and return data.

See the below example..

var fruits = ["apple", "orange", "cherry"];

document.getElementById("demo").innerHTML = getData(fruits);

function getData(fruits) {
  var str = "";

  fruits.forEach(function(item, index) {
    str += index + ":" + item + "<br>";
  });

  return str;
}
<span id="demo" />

Solution 3:[3]

Return value The return value of arr.forEach function is always undefined var fruits = ["apple", "orange", "cherry"];

document.getElementById("demo").innerHTML = getData(fruits);

function getData(fruits) {
  var str = "";

  fruits.forEach(function(item, index) {
    str += index + ":" + item + "<br>";
  });

  return str;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adiga
Solution 2 adiga
Solution 3 Shubham Sonar