javascript foreach return value code example

Example 1: foreach jas

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

Example 2: foreach javascript

let names = ['josh', 'joe', 'ben', 'dylan'];
// index and sourceArr are optional, sourceArr == ['josh', 'joe', 'ben', 'dylan']
names.forEach((name, index, sourceArr) => {
	console.log(color, idx, sourceArr)
});

// josh 0 ['josh', 'joe', 'ben', 'dylan']
// joe 1 ['josh', 'joe', 'ben', 'dylan']
// ben 2 ['josh', 'joe', 'ben', 'dylan']
// dylan 3 ['josh', 'joe', 'ben', 'dylan']

Example 3: 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 4: what foreach method returns in javascript

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

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

Example 5: mdn foreach

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

Example 6: foreach javascript

Used to execute the same code on every element in an array
Does not change the array
Returns undefined