Loops: while and for

Loops: while and for

JavaScript Loops: while and for

Loops are used to execute a block of code multiple times until a condition is met.

1️⃣ while Loop

Repeats while a condition is true.

Syntax

while (condition) { // Code to execute }

Example: Print numbers 1 to 5

let i = 1; while (i <= 5) { console.log(i); i++; // Increment `i` to avoid infinite loop }

📌 Output:

1 2 3 4 5

🔹 Explanation:

  • Starts at i = 1
  • Runs until i <= 5 becomes false
  • i++ increases i after each loop

2️⃣ do...while Loop

Executes at least once, then repeats while the condition is true.

Syntax

do { // Code to execute } while (condition);

Example: Run at least once

let num = 10; do { console.log(num); num++; } while (num < 5);

📌 Output:

10

🔹 Explanation:

  • Runs once, even though num < 5 is false
  • Useful when code should execute at least once

3️⃣ for Loop

Repeats a fixed number of times.

Syntax

for (initialization; condition; increment) { // Code to execute }

🔹 Breakdown:

  • initialization → Start the loop
  • condition → Run while true
  • increment → Change variable each loop

Example: Print numbers 1 to 5

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

📌 Output:

1 2 3 4 5

4️⃣ for vs. while

Featurewhile Loopfor Loop
Use CaseWhen the number of iterations is unknownWhen the number of iterations is known
StructureCondition onlyInitialization, condition, increment in one line
Examplewhile (x < 10) {...}for (let i = 0; i < 10; i++) {...}

5️⃣ for...of Loop (For Arrays & Iterables)

Loops through values in an array.

let fruits = ["Apple", "Banana", "Cherry"]; for (let fruit of fruits) { console.log(fruit); }

📌 Output:

Apple Banana Cherry

6️⃣ for...in Loop (For Objects)

Loops through keys in an object.

let person = { name: "John", age: 30, city: "New York" }; for (let key in person) { console.log(`${key}: ${person[key]}`); }

📌 Output:

name: John age: 30 city: New York

7️⃣ Loop Control: break & continue

break → Stop the loop completely

for (let i = 1; i <= 5; i++) { if (i === 3) break; // Stop when `i` is 3 console.log(i); }

📌 Output:

1 2

continue → Skip current iteration

for (let i = 1; i <= 5; i++) { if (i === 3) continue; // Skip `3`, continue looping console.log(i); }

📌 Output:

1 2 4 5

🎯 Summary

whileUse when iterations are unknown
do...whileRuns at least once
forUse when iterations are known
for...ofLoop over arrays & iterables
for...inLoop over object properties
breakStop loop | continueSkip iteration

🚀 Now you're ready to use loops in JavaScript! Let me know if you need help. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close