Skip to content

Instantly share code, notes, and snippets.

@zkat
Last active July 13, 2016 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zkat/c54c507451a5056a4d53 to your computer and use it in GitHub Desktop.
Save zkat/c54c507451a5056a4d53 to your computer and use it in GitHub Desktop.
Short guide to iteration functions!
var arr = [1,2,3,4]
// Array#map is for going from array A, to array-of-same-length B, with no side-effects.
var arrPrime = arr.map(function (num) { return num + 1 })
// forEach doesn't return anything useful (just `undefined`), so we use it for "side-effects".
var otherArr = []
arr.forEach(function (num) {
if (num % 2 !== 0) {
otherArr.push(num) // this is a side-effect
} else {
console.log(num) // this is also a side-effect
}
})
// for loops are good for iteration gymnastics, or when there's no array to start from!
var finalArr = []
for (var i = 0; i < 10; i++) {
if (i % 2 === 0) {
i++
}
finalArr.shift(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment