For, for...in, for...of, and forEach loops - tdkehoe/blog GitHub Wiki
In addition to for loops, JavaScript also has for in, for of, and forEach loops.
#for loops
for loops have three optional expressions, which are similar to arguments in a function:
-
initialization is typically
var i = 0 -
condition tells the loop when to end , e.g.,
i < 9 -
final-expression tells the loop what to do at the end of each loop iteration, typically
i++
for loops also have a statement inside curly brackets, e.g.,
for (var i = 0; i <9; i++) {
console.log(i);
}
#for...in loops
for...in and for...of iterate over objects (not arrays).
-
for...initerates over the keys of the properties in the object. It was in the original JavaScript. -
for...ofiterates over the values of the properties in the object.for...ofwas new in ES2015.
It's best to use let instead of var in for...in loops.
forEach() iterates over arrays. It was new in ES5.1.
var posts = [a:"Best Nut Recipes", b:"Click-Baiting for Small-Brain Bass", c:"Escalator Running"];
for (let post in posts) {
console.log(post);
}