Newby Coder header banner

Javascript Loops


Programming loop is a functionality of doing same thing over and over again, that is, repetitive tasks where each repetition is termed as an iteration

A loop usually has one or more of following features:

In pseudocode, this looks something like:

loop(food = 0; foodWasted = 10) {
  if (food >= foodWasted) {
    exit loop;
    // enough food wasted
  } else {
    food += 2; // waste 2 more food
    // same loop runs for updated food value
  }
}

for loop

for loop has following syntax:

for (initializer; exit-condition; final-expression) {
  // code to run
}

It contains :

  1. keyword for, followed by some parentheses
  2. Inside the parentheses there are three items, separated by semi-colons:
    • An initializer — this is usually a variable set to a number, which is incremented to count the number of times a loop has run, sometimes referred to as a counter variable
    • An exit-condition — this defines a condition based on which loop is to be stopped
    • A final-expression — this is always evaluated (or run) each time a loop has gone through a full iterationIt modifies counter variable to bring it closer to exit condition value
  3. Some curly braces that contain a block of code — this code is to be run for each iteration of loop

Example

Print each fruit of a fruit list to browser's console

var fruits = ["lemon", "orange", "melon"]
for (var i = 0; i < fruits.length; i++) {
  console.log(fruits[i])
}

Output

lemon
orange
melon

Given example shows a loop being used to iterate over the items in an array and do something with each of them

In case value of i is not updated, then loop keeps on running which can crash or freeze the browser

Such a situation is known as an infinite loop

break statement

break statement is used to exit a loop

Following example uses break to exit a while loop when value of i is 3:

i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1 

continue statement

continue statement skips to next iteration of a loop, omitting (execution of) statements(s) appearing after it in a loop

Following example logs from 1 to 7, except 2 and 5

Example

Continue to the next iteration if i is 3:

i = 0
for(var i=0; i < 7; i++) {
    i += 1
    if (i == 2 || i == 5):
        continue
    console.log(i)
}

This produces following output

1
3
4
6
7 

while and do - while

while is another type of loop available in JavaScript

Syntax :

initializer
while (exit-condition) {
  // code to run

  final-expression
}

This works in a similar way to a for loop, except that the initializer variable is set before loop, and final-expression is included inside loop after the code to run — rather than these two items being included inside parentheses

exit-condition is included inside parentheses, which are preceded by while keyword rather than for

Same three items are still present, and they are still defined in same order as they are in for loop — final-condition is then run after code inside loop has run (an iteration has been completed), which only happens if exit-condition has still not been reached

var count = 0
while(count <9):
    console.log('The count is:', count)
    count = count +1 

When above code is executed, it produces following result -

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8 

In above example an indexing variable count is defined which is set to 0

The block consisting of console.log() and increment statements, is executed repeatedly until count is no longer less than 9

For each iteration, value of count is displayed and then increased by 1


do ... while loop

do...while loop provides a variation on the while structure:

In a do...while loop, code inside curly braces is run before check is made to see if it should be executed again

In while and for, check comes first, so code might not be executed

initializer
do {
  // code to run

  final-expression
} while (exit-condition)

Initializer comes before loop starts

do keyword directly precedes curly braces containing code to run and final-expression

while keyword with exit-condition comes after closing parenthess

var count = 0;
do {
  console.log('The count is:', count)
  count++;
} while (count < 9);