-
Notifications
You must be signed in to change notification settings - Fork 0
For, for...in, for...of, and forEach loops
Thomas David Kehoe edited this page Dec 3, 2016
·
2 revisions
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...in
iterates over the keys of the properties in the object. It was in the original JavaScript. -
for...of
iterates over the values of the properties in the object.for...of
was 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);
}