Types of loops in JS
Programming is all about solving problems efficiently. Two concepts that play a major role in writing reusable and efficient programs are loops and functions . Loops help us perform repetitive tasks without writing the same code again and again, whereas functions help us organize code into reusable blocks. Let's understand these concepts in detail. Why Do We Need Loops? Suppose we want to print "Hello" five times. Without loops, we would write: console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); Although this works, it violates one of the fundamental principles of programming: Don't Repeat Yourself (DRY) Repeating code: Increases the number of lines. Makes maintenance difficult. Introduces more chances for errors. Loops solve this problem by allowing us to execute the same block of code multiple times. Types of Loops in JavaScript JavaScript provides three looping statements: Loop Type Category while Entry-Check Loop for Entry-Check Loop do...while Exit-Check Loop Entry-Check Loop / Entry-Controlled Loop In entry-Check loops, the condition is checked before executing the loop body. If the condition is false initially, the loop body never executes. Examples: while loop for loop Exit-Check Loop / Exit-Controlled Loop In an exit-Check loop, the loop body executes first and then checks the condition. Therefore, the body executes at least once. Example: do...while loop Components of Every Loop Every loop generally consists of three parts: 1. Initialization Determines where the loop starts. let i = 1 ; 2. Condition Determines whether the loop should continue executing. i <= 5 3. Increment or Decrement Updates the loop variable after each iteration. i ++ ; or i -- ; 1. while Loop The while loop repeatedly executes a block of code as long as the condition remains true. Syntax while ( condition ) { // statements } Example: Print Numbers from 1 to 5 let i = 1 ; while ( i <= 5 ) { cons