foreach return js code example

Example 1: foreach javascript

var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});

Example 2: javascript foreach index

users.forEach((user, index)=>{
	console.log(index); // Prints the index at which the loop is currently at
});

Example 3: js for each item do

let array = ['Item 1', 'Item 2', 'Item 3'];

array.forEach(item => {
	console.log(item); // Logs each 'Item #'
});

Example 4: forEach

const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.

Example 5: javascript forEach return

const list = [{ name: "John", age: 36 },{ name: "Jack", age: 17 }];

// if you just have to FIND an object with a specific value,
// use Array.prototype.find:
const foundHim = list.find( person => person.name === "John" );
console.log( foundHim );

// if you still want to / need to RETURN the object / value
let returnedHim;
list.forEach( person => {
  if ( person.age === 17 ) {
    returnedHim = person;
  }
});

console.log( returnedHim )

Example 6: what foreach method returns in javascript

function double(arr) {
  return arr.forEach(num => num*2);
}

console.log(double([1,2,3,4])) //undefined