Skip to content

Instantly share code, notes, and snippets.

@larrybolt
Created February 16, 2018 17:31
Show Gist options
  • Save larrybolt/e68226a21aaceeb322f7d8f4d833bf11 to your computer and use it in GitHub Desktop.
Save larrybolt/e68226a21aaceeb322f7d8f4d833bf11 to your computer and use it in GitHub Desktop.
javascript map and forEach examples with for and ECMA6
// we have an array, with items
const items = [
'ethan',
'larry',
'katrijn',
'janice'
];
// To go and print all of them
/* Regular, old way of doing it */ console.log("\n\n 1")
for (let i = 0; i<items.length; i++){
console.log(items[i])
}
/* a bit easier */console.log("\n\n 2")
items.forEach(function(item) {
console.log(item)
})
/* using new syntax */console.log("\n\n 3")
items.forEach((item) => {
console.log(item)
})
/* even less syntax to still do the same */console.log("\n\n 4")
items.forEach(item => console.log(item))
/* and even less... */console.log("\n\n 5")
items.forEach(console.log)
// the reason it prints more, is because the arguments that forEach passes
// the the function are: currentElement, index, fullArray
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
/* which means it's actually doing: */console.log("\n\n 5b")
items.forEach(function(current, index, all) { console.log(current, index, all)})
// forEach basically just goes over every element,
// there's tons of other array functions we can use such as map/filter/reduce
/* as an example, to capitalise each word */ console.log("\n\n 6")
items.map((item) => item.toUpperCase()).forEach(console.log)
// map takes an array, and applies an action for every item,
// and then return a new array
/* using the old syntax, from 2 */console.log("\n\n 7")
items
.map(function(item) { return item.toUpperCase()})
.forEach(function(item) { console.log(item) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment