Looping is traversing in a specified range. For example we can loop thrugh an array to print array elements or we can count from 1 to 100 by looping and print the number.
For Loop
One of the most used loop type is for loop.
for(i=1;i<11;i++){ console.log(i); }
- for is our loop keyword and between ( ) is the loop instructions
- i=1 is an initialization where loop will start
- i<11 is condition where in every step will be checked. If i is not lower than 11 the loop will be ended
- i++ is status update where in each step will incremented
- This loop will print from 1 to 10
While Loop
While loop is loops through while specified state is true.
status=true; while(status){ console.log("Status is true"); }
- while is the loop start
- status is the condition for the loop. Loop will resume is status returns true. When status is false loop will stop
- “Status is true” will be written to the console endlessly
For In Loop
This is second type of for loop. Previously in for loop we have given start number, step and end number of the loop. For in loops iterates over a collection like array.
fruits=["lemon","apple","berry"]; for(a in fruits){ console.log(a); }
- for will iterate according to ( ) condition
- fruits is the collection we want to iterate
- in is the keyword used to specify collection
- a is the variable provide data for each step
- As output fruits array will be printed to the console.