Skip to main content
  • To perform repeated actions , to automate tasks

Types of Loops

  • The for loop
    •   for (statement 1 ; statement 2 ; statement 3) {
                // code to be executed
            }
      
    • statement 1 is executed one time
    • statement 2 is condition based on which loop runs
    • statement 3 is executed everytime the loop body gets executed
    •   // Program to add first n natural numbers
        let sum = 0 ;
        let n = 100;
      
        for (let i = 1 ; i <= n ; i ++) {
      
            console.log(i);
            sum += i ;
            console.log("sum of first "+ i +" Natural number is", sum);
        }
      
  • For in Loop
    • works on objects and arrays
    •   // For in loop
      
        let obj = {
            kalyan : 10,
            kiran : 8,
            suma : 5,
            raj : 9
        }
        for (let a in obj) {
            console.log("Keys of obj are " + a + ", Values are " + obj[a]);
        }
      
  • For off loop
    • works on strigs and arrays , they should be iterable
    •   // For off loop th obj should be iterarable like string or array
        // Works on arrays and strings
        for (let b of "kalyan") {
            console.log(b);
        }