javascript forEach function code example

Example 1: javascript foreach

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})

Example 2: javascript foreach object

const list = {
  key: "value",
  name: "lauren",
  email: "[email protected]",
  age: 30
};

// Object.keys returns an array of the keys
// for the object passed in as an argument.

Object.keys(list).forEach(val => {
  let key = val;
  let value = list[val];
  console.log(`${key} : ${value}`);
});

// Returns:
// "key : value"
// "name : lauren";
// "email : [email protected]"
// "age : 30"

Example 3: javascript foreach

var colors = ['red', 'blue', 'green'];

colors.forEach(function(color) {
  console.log(color);
});

Example 4: foreach javascript

let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four

Example 5: javascript foreach example

var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
    console.log(color);
});

Example 6: foreach javascript

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

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

Tags:

Php Example