Module 4: Control Flow – Conditionals and Loops
Loops: for, while, do...while
Loops are used to execute a block of code repeatedly.
1. for
loop:
Often used when you know how many times you want the loop to run.
Syntax: for (initialization; condition; finalExpression) { // code block }
initialization
: Executed once before the loop starts (e.g.,let i = 0
).condition
: Evaluated before each iteration. Iftrue
, the loop continues.finalExpression
: Executed at the end of each iteration (e.g.,i++
).
for (let i = 0; i < 5; i++) { console.log("Iteration number " + i); } // Output: // Iteration number 0 // Iteration number 1 // ... // Iteration number 4
2. while
loop:
Repeats a block of code as long as a specified condition is true
.
let count = 0; while (count < 3) { console.log("Count is " + count); count++; } // Output: // Count is 0 // Count is 1 // Count is 2
Ensure the condition eventually becomes false
to avoid an infinite loop.
3. do...while
loop:
Similar to while
, but the code block is executed at least once before the condition is checked.
let num = 5; do { console.log("Number is " + num); num++; } while (num < 5); // Condition is false, but block ran once. // Output: Number is 5