Home » javascript » Loop (Iteration) Statements in JavaScript

Loop (Iteration) Statements in JavaScript

Loop(Iteration) Statement

A loop describes the process in a software program/script that repeats the same set of instructions over and over until it receives the order to stop.

Loops offer a quick and easy way to execute something repeatedly. There are 4 types of loop in JavaScript:

  • for statment
  • for/in statement
  • while statment
  • do/while statement

for Statement

The for is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.

Example of for statement

For/in Statement

  • This statement loops through the properties of an object.
  • The block of code snippet inside the loop will be executed once for each of the properties.

While Statement

  • while is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.
  • Initialization of loop variable is mandatory before writing while loop.

Example of while statment

do-while Loop

  • It loops through a block of code once at first and then repeats the loop while the specified condition is true.
  • The main difference between do-while and while loop is that in do-while loop, the set of statements are executed at least once even if the condition isn’t satisfied whereas in while loop nothing is executed if the condition is false.

Example: of do while statement

Nested Loops

An important fact is that both break and continue affect the current loop.

So while working with the nested loops, things can get confusing very quickly.

Consider the following example below:

Note:

  • We have got 2 loops here. Each loop runs for 5 times i.e., 0–4.
  • The first loop will continue if i is even i.e., the only values of i that can ever be logged are 1 & 3 as 0, 2, and 4 will not pass the even criteria: if (i % 2 == 0).
  • Now, the inner lop breaks when j is 2. So, the values of j can only be 0 & 1.

So finally the printed output is:

Managed by MochaHost - Fast & Easy WordPress Hosting