JavaScript Loops


Loops are used to repeatedly run the same piece of code as long as a predetermined condition is satisfied. A loop's main purpose is to save time and effort by automating the repetitive processes within a program.

The ability to execute a collection of instructions or functions repeatedly while a certain condition is true is known as looping in programming languages. Let's say we wish to print "Hello World" ten times, for instance.

Currently, JavaScript offers five different kinds of loops:

  1. while: executes a block of code repeatedly so long as the given condition evaluates to true.
  2. do…while: executes a block of code once in a loop before evaluating the condition. The statement is repeated as long as the provided condition is true if the condition is true.
  3. for: cycles through a code block until the counter reaches a certain value.
  4. for…in: iterates over an object's attributes.
  5. for…of: loops through Iterable objects like strings, arrays, etc.

1. The while Loop

The simplest looping statement offered by JavaScript is this one. While the stated condition evaluates to true, the while loop iterates across the block of code in question. The loop ends as soon as the condition fails.

The general syntax is as follows:  

Syntax

Example

Preview

2. The do...while Loop

A variation of the while loop that examines the condition at the conclusion of each loop iteration is the do-while loop. A do-while loop repeats a statement as long as the supplied condition evaluates to true after executing a block of code once and before determining if the condition is true.

Syntax

Example

Preview

3. The for Loop

As long as a specific condition is satisfied, the for loop repeats a section of code. It is often employed to run a code block a certain number of times.

The parameters of the for loop statement have following meanings:

  1. initialization: it sets the counter variables to their initial values and is evaluated once before the body of the loop is first executed.
  2. condition: this variable is assessed at the start of each iteration. The loop statements run if it evaluates to true. The loop will stop executing if it evaluates to false.
  3. increment: it adds a fresh value to the loop counter each time it executes.

Syntax

Example

Preview

4. The for...in Loop

The for-in loop is a particular kind of loop that iterates over an object's attributes or an array's items.

The for-in loop counter, or variable, is a string rather than a number. It includes the index of the current array element or the name of the current property.

Syntax

Example

Preview

5. The for...of Loop ES6

A new for-of loop introduced in ES6 makes it very simple to iterate over arrays and other iterable objects (like strings). Every member of the iterable object receives an execution of the code contained within the loop.

Example

Preview