SiteMap  | About    

JavaScript Loops

Looping is a fundamental programming idea that is commonly used in writing programs. A loop is a sequence of instruction s that is continually repeated until a certain condition is reached. It offers a quick and easy way to do something repeatedly.

There are four loops in JavaScript programming:

  1. for loop
  2. for-in loop
  3. while loop
  4. do-while loop

JavaScript for..loop

Javascript for loop is the most widely used type of loop and it repeats until a specified condition evaluates to false.



  1. i=1 : initialization
  2. i < =5 : condition
  3. i++ : increment

When you run the above program it will display number 1 to 5 in message box.

JavaScript for-in loop

JavaScript for-in loop is convenient to use with arrays or object, and it enables the user to loop through each element in the array with having to know the number of element the array actually contains. Rather than working with index number of each element, it automatically moves to the next index with each iteration.



JavaScript while loop

JavaScript while loops can execute a block of code as long as a specified condition is true. It enables you to test a condition and keep on looping when it meets the specified condition . The loop will terminate when its condition evaluates to false.



Javascript do..while loop

The do-while loop is executed at least once whereas the while loop may not execute at all. That means, it will execute the code block once, before checking if the condition is true , then it will repeat the loop as long as the condition is true.



When you run the above example, it will execute one time even though the condition is not met (i>5).

Difference between while loop and do while loop

A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Whereas a while loop will check the condition first before executing the content.

Javascript Infinite Loop

A loop that repeats indefinitely and never terminates is called an Infinite loop or endless loop.

In JavaScript, by omitting all parts of the head, the loop can also become infinite:

You can use a while loop as infinite loop:

Javascript Break statement

Executing the break statement exits from the current loop or statement , and begins script execution with the statement immediately following.



Javascript Continue statement

Javascript Continue statement stops the current iteration of a loop, and starts a new iteration.


output (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.