Loops Introduction in Javascript

Rumman Ansari   Software Engineer   2023-03-26   6383 Share
☰ Table of Contents

Table of Content:


Loops provide a quick and effortless way to repeat certain operations. Let us see some of the important loops in JS

  1. for statement
  2. while statement
  3. do...while statement
  4. For of loop
  5. For in Loop
  6. For Loop

    Syntax

    
    
     for ([initialization]; [condition]; [final-expression])
       statement
    
    
    • Initialization - An expression to initialize counter variable
    • condition - An expression to evaluate every loop iteration
    • final-expression - An expression to update the counter variable

    Example:

        for (var i = 0; i < 9; i++) 
        {
                console.log(i);
                // more statements
        }
    

    While Loop

    Syntax

     while (condition) { statement} 

    Example:

        var n = 0;
        var x = 0;
        while (n < 3) {
             n++;
             x += n;
     }
    

    Do... While Loop

    Syntax

    do statement while condition 

    Example:

     var i = 0;
        do {
         i += 1;
         console.log(i);
        } while (i<5); 
    Assignment 1
    • Write a program to draw a chessboard of size 8X8.
    • Each line of the chessboard should have a + and a - . + indicates black cell and - indicates a white cell on the chess board.
    • Draw a border with * on all four sides.
    • You can try this using different loops.