Different loops in JavaScript

learning javascript basics kodementor

Loops help to automate repetitive tasks in programming until the certain condition is met. JavaScript provides different types of looping to run a block of code.

Loop Types in JavaScript

  • for loop
  • for in loop
  • while loop
  • do-while loop

Let’s dive into details on each type.

1: for Loop

for loop is a most frequently used loop in javascript. It consists of 3 parts i.e.loop initializer, test statement and iteration statement. loop initializer is executed only once before the loop begins. test statement helps to determine whether a condition is true or not. If the condition is true, code inside of loop is executed else code inside loop is escaped. Lastly, iteration statement is used to increment or decrement the value of test statement. This is executed on every loop.

Syntax of for loop

Example of for loop

2: for in loop

for in loop iterate through the properties of object. The block of code inside the loop will be executed once for each property.

Syntax of for..in loop

Example of for..in loop

3: while loop

while loop is also frequently used loop in javascript. While loop executes a block of code as long as the condition specified is true.

syntax of while loop

Example of while loop

4: do-while loop

do-while loop is similar to while loop except that the condition check done at the end of loop. Due to this, block of code inside loop is executed at least once.

syntax of do-while loop

Example of do-while loop

Below is a simple example of do-while loop.

Hope you understand the loops in javascript. You can learn more about basics of javascript in this article. Happy Coding 🙂