Three common types of loops in JavaScript are for
, forEach
, and while
loops. for
loops are probably the most popular, although forEach
loops have become more popular recently.
The examples of each below will use this fruits array as an example:
var fruits = ["apple", "grape", "mango", "banana"];
for
loops have a lot going on:
for (var i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This is relatively analogous to an while
loop in ruby (although JavaScript has a while
loop too):
i = 0
while i < fruits.length
p fruits[i]
i += 1
end
Things to note here are:
i
is incremented with a++
operator in JavaScript;i += 1
syntax works as well but is less commonfor
takes three arguments: the initialization of a variable, a condition that must evaluate to true for the loop to continue, and how the inititialized variable should be incremented (i += 2
,i--
, and others are also allowed)
Alternative syntaxes include:
var i;
for (i = 0; i < fruits.length; i++) {}
var i = 0;
for (; i < fruits.length; i++) {}
for (let i = 0; i < fruits.length; i++) {}
The first statement in the parenthesis runs before the loop begins and then never again, so you can also lift the logic that would go there up to a higher line. let
is like var
but creates a variable with more limited scope (let
and const
were introduced to JavaScript as part of ES6).
The parenthesis and curly braces in forEach
loops can be confusing, so take a look at an empty loop first:
fruits.forEach(function() {
});
forEach
takes as an argument another function (an anonymous function). That function has a single parameter, which is analogous to a ruby block variable. All logic for the loop goes inside the function's curly braces:
fruits.forEach(function(fruit) {
console.log(fruit);
});
Note that:
- the parenthesis opened after
forEach
is closed on the last line of the loop - the parenthesis opened after
function
is closed on the same line after the block variable - the curly brace is opened on the end of the line containing
forEach(function( ...
and closed on the last line of the loop immediately before the last parenthesis is closed
while
loops in JavaScript are almost identical to while
loops in ruby:
var i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
}
Note also the similarities between JavaScript's while
and for
loops. A while
loop is less common but is ideal for situations where i
should not be incremented the same every time through the loop:
var i = 0;
while (i < 100) {
if (i % 3 === 0) {
i += 2;
} else {
i += 1;
}
}