Answers for "do something with each value of an array js"

179

javascript array foreach example

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

Code answers related to "do something with each value of an array js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language