JavaScript Loops are used to repeatedly run a block of code - until a certain condition is met. When developers talk about iteration or iterating over, say, an array, it is the same as looping.
JavaScript offers several options to repeatedly run a block of code, including
while
, do while
, for
and for-in
.
Here is an example of a JavaScript while
loop.
var sum = 0;
var number = 1;
while (number <= 50) { // -- condition
sum += number; // -- body
number++; // -- updater
}
console.log("Sum = " + sum); // => Sum = 1275
The condition is first evaluated. If true, the block of statements following the while
statement is
executed. This is repeated until the condition becomes false. This is known as a pre-test loop
because the condition is evaluated before the block is executed.
The number++
statement is called the updater. Removing it will result
in an infinite loop. You must always include a statement in a loop that guarantees the termination
of the loop or else you'll run into this problem.
Next is an example of a JavaScript do while
loop:
var sum = 0;
var number = 1;
do {
sum += number; // -- body
number++; // -- updater
} while (number <= 50); // -- condition
console.log("Sum = " + sum); // => Sum = 1275
The block following do is executed first and then the condition is evaluated. If the while condition is true, the block is executed again and repeats until the condition becomes false. This is known as a post-test loop as the condition is evaluated after the block has executed.
The do while
loop is executed at least once whereas the while
loop may not execute at all.
The do while
is typically used in a situation where the body of a loop contains a statement that
generates a value that you want to use in your conditional expression, like this:
do { // read a character from keyboard in the body } while (if ch === '0'); // => terminate loop if '0' is entered
The most frequently used loop in JavaScript is the for
loop. Here is an example:
var sum = 0;
for (var i = 1; i <= 50; i++) {
sum = sum + i;
}
console.log("Sum = " + sum); // => Sum = 1275
It consists of three parts, separated by semicolons. The first is the initializer (var i = 1) which initializes the loop and is executed only once at the start. The second is a test condition (i <= 50). When a conditional expression evaluates to true, the body of the loop is executed. When false, the loop terminates. The third part is an updater (i++) which is invoked after each iteration. The updater typically increments or decrements the loop counter.
In a for
loop, all three parts i.e. initializer, test condition, and updater are written together
in a single line (called an iteration statement), whereas in a while
, they're scattered and lie
at different places. This makes a for
loop more readable than a while
loop and as
a result, more easily maintainable.
So when do we use for
and when while
? If the number of iterations is known use
the for
loop. If you want to loop until a certain condition is met use the while
loop.
A for-in
loop iterates through the properties of an object and executes the loop's body
once for each enumerable property of the object. Here is an example:
var student = { name: "Bill", age: 25, degree: "Masters" };
for (var item in student) {
console.log(student[item]); // => "Bill", then 25, then "Masters"
}
With each iteration JavaScript assigns the name of the property (a string value) to the variable item.
In the example above these are: name
, age
, and degree
.
Note that for-in
loops also return properties and methods that are inherited through the
prototype chain. An easy way to skip properties and functions that are not part of the object itself use
the built-in hasOwnProperty
method.
var Student = function (name) {
this.name = name;
}
Student.prototype.age = 38;
var student = new Student("Carl");
for (var item in student) {
if (student.hasOwnProperty(item)) {
console.log(student[item]); // => Carl. age is not displayed
}
}
We have not discussed objects yet, but the student object has a name
property on the object itself.
Its prototype object has an age
property. The for-in
loop iterates over all properties, but the
hasOwnProperty
ensures that the age
property on the prototype does not get
displayed because it is not student's own property.
When JavaScript encounters a break
statement in a loop it immediately exits the loop without
executing any other statements in the loop. Control is immediately transferred to the statement
following the loop body. Here is an example:
var sum = 0;
for (var i = 1; i <= 10000; i++) {
sum += i;
if (i === 50) {
break; // immediately transfers control outside the for block
}
}
console.log("Sum = " + sum); // => Sum = 1275
When an infinite loop is created intentionally, you can use a break
statement to controls termination
of the loop, like so:
var number = 1;
var sum = 0;
while (true) // equivalent to for ( ; ; ), called 'forever' loop
{
sum += number;
if (number === 50) {
break; // immediately transfers control outside while block
}
number++;
}
console.log("Sum = " + sum); // => Sum = 1275
The number++;
statement won't be executed when the loop is entered for the 50th time.
When JavaScript encounters a continue
statement in a loop it stops the execution of
the current iteration
and goes back to the beginning of the loop to begin the next iteration. The example below displays
only even numbers.
for (var i = 1; i <= 10; i++) {
if ((i % 2) != 0) {
continue;
}
console.log(i); // => 2, 4, 6, 8, 10
}
The continue
statement can also be used in other loops. However, in a for
loop
it behaves differently
from when used in a while
loop. In the example above, the for
loop first
evaluates the i++ expression
and then tests the i <= 50 condition. Now, consider the while
loop:
var number = 0;
while (number <= 10) {
number++;
if ((number % 2) != 0) {
continue;
}
console.log(number); // => 2, 4, 6, 8, 10
}
When the continue
statement is executed, the control is returned directly to the while (number <= 50)
test condition and the number++ expression is not evaluated, thus causing an infinite loop. The lesson
here is that you cannot simply replace a for
loop with a while
loop; you
have to be careful especially when a continue
statement is involved.