Answers for "js foreach fucntion"

179

javascript foreach

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
Posted by: Guest on April-27-2020
1

array.foreach

let arr = [1,2,3]

// forEach accepts a function, and each value in array is passed to the 
// function. You define the function as you would any regular
// function, you're just doing it inside the forEach loop
arr.forEach(function(value){
  console.log(value)
})

// you also have access to the index and original array:
arr.forEach(function(value, idx, array){
  console.log(idx, value, array)
})

// it's common for the arrow notation to be used: it's effectively
// the same thing but the function keyword is removed and the syntax is
// a bit different
arr.forEach((value) => {
  console.log(value)
})
Posted by: Guest on January-25-2022
12

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']
Posted by: Guest on May-23-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language