6. Loops and Iterations in Javascript

  1. for loop

    The for loop is commonly used when the number of iterations is known.

for (let i = 0; i < 5; i++) {
    console.log(i);
}
  1. while loop

    The while loop executes as long as the specified condition is true.

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
  1. do while loop

    The do...while loop ensures that the loop body executes at least once, even if the condition is false.

let i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);
  1. for...in Loop

    The for...in loop iterates over the properties of an object.

let object ={
  name:"Ayush",
  lastName:"Rajput",
  age: 21,
}

for(let key in object){
console.log(key + "->" + object[key])
}

/* Output
name->Ayush
lastname->Rajput
age:21
 */

In JS arrays are nothing they are objects so we also iterate over array using for..in loop

let arr = [ 1,2,3,4]
arr.myprop = "Hello"
console.log(arr);

for(let key in arr){
        console.log(key + "->" + arr[key]);  // here key is array indexs
}

/* Output 
[ 1, 2, 3, 4, myprop: 'Hello' ]
0->1
1->2
2->3
3->4
myprop->Hello 
*/
  1. for...of Loop

    The for...of loop is used for iterating over iterable objects like arrays, strings, maps, sets, etc.

const arr = [10, 20, 30];

for (let value of arr) {
    console.log(num);
}


/*output
10
20
30
  1. Break and Continue

    The break statement terminates the loop immediately.

    The continue statement skips the current iteration and moves to the next one.

Interview Questions

  1.   // what will be the output
      for (var i = 0; i < 3; i++) {  
          setTimeout(() => console.log(i), 1000);
      }
    
      /*
      3
      3
      3
    

    Explanation: Since var is function-scoped, the loop completes first, setting i = 3, and only then do the setTimeout functions execute, all printing 3.

    If we use let in place of var then output will be : 0, 1,2

    Since let is block-scoped, a new i is created for each loop iteration.

  2. What is the difference between for...in and for...of?

for..infor..of
Iterate overKeys of an object or arrayValues of an iterable
Suitable forObjectsArrays, strings, maps, sets
Examplefor (let key in obj) {}for (let value of arr) {}
  1. What is infinite loop ? Give example .

    A loop that never ends due to a missing exit condition.

     while (true) {
         console.log("Infinite loop");
     }
    

Next Topic

7. Conditional statements and Exception handling