JavaScript for Loop Control Statement

Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over and over again, each time with a different value.

The ‘for‘ loop is the most compact form of looping. It includes the following three important parts −

  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
  • The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
  • The iteration statement where you can increase or decrease your counter.

For loop is primarily preferred when the number of iterations are well known in advanced.

Syntax:

  1. Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
  2. Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  3. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
  4. Increment/ Decrement: It is used for updating the variable for next iteration.
  5. Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.

Flow Chart:

javascript for loop flow chart diagram

Program example –

Output –

 

Leave a Reply

Your email address will not be published. Required fields are marked *