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);
});
Example 3: js for each item do
let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(item => {
console.log(item);
});
Example 4: forEach
const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach((element) => {
console.log(element)
numCallbackRuns++
})
console.log("numCallbackRuns: ", numCallbackRuns)
Example 5: javascript forEach return
const list = [{ name: "John", age: 36 },{ name: "Jack", age: 17 }];
const foundHim = list.find( person => person.name === "John" );
console.log( foundHim );
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]))