Sunday, June 15, 2025

Javascript Module 8

  Module 8 : Loops: for, while, do...while 

understand how to use loops (for, while, and do...while) in JavaScript to repeat a block of code efficiently, explore use cases, syntax.

πŸ“˜ What Are Loops?









Loops are control structures that allow you to repeat a block of code multiple times until a certain condition is met.

They are essential in:

Iterating over arrays and collections

Automating repetitive tasks

Controlling program flow


1️⃣ for Loop

πŸ”§ Syntax:

javascript

 code

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

✅ Explanation:

Initialization: sets a starting point (e.g., let i = 0)

Condition: loop runs as long as this is true

Increment: updates the loop counter (i++)

πŸ”„ Flowchart:

Initialize variable

Check condition

If true, run block

Increment variable

Repeat until condition is false

πŸ§ͺ Example:

javascript

code

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

Output:

makefile

code

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5



✅ Use Case:

When the number of iterations is known in advance.


2️⃣ while Loop


πŸ”§ Syntax:








javascript

code

while (condition) { // code block to execute }

✅ Explanation:

Checks the condition before executing.

Runs as long as the condition is true.

πŸ§ͺ Example:

javascript

 code

let i = 1; while (i <= 5) { console.log("While Count: " + i); i++; }

Output:

mathematica

code

While Count: 1

While Count: 2

While Count: 3

While Count: 4

While Count: 5



✅ Use Case:

When the number of iterations is not known ahead of time.


3️⃣ do...while Loop

πŸ”§ Syntax:

javascript

code

do { // code block to execute } while (condition);

✅ Explanation:

Executes the code block at least once before checking the condition.

πŸ§ͺ Example:

javascript

code

let i = 1; do { console.log("Do...While Count: " + i); i++; } while (i <= 5);

Output:

mathematica

 code

Do...While Count: 1

Do...While Count: 2

Do...While Count: 3

Do...While Count: 4

Do...While Count: 5



✅ Use Case:

When you need to run code once no matter what.


🧠 Understanding & Insights


Loop Type

Runs at least once?

Best for

Control Point

for

No

Known iteration count

Pre-check

while

No

Unknown iteration count

Pre-check

do...while

Yes

At least one execution

Post-check


Avoid infinite loops: Always ensure your loop makes progress toward ending.

Performance consideration: for loops are slightly more optimized in some engines when iteration count is known.

πŸ“š  Tip:

According to V8 JavaScript engine benchmarks, for loops with fixed bounds often perform better due to loop unrolling and optimization.


  Exercises

πŸ” Exercise 1: Sum of Numbers from 1 to N using a for loop



javascript

code

function sumToN(n) { let sum = 0; for (let i = 1; i <= n; i++) { sum += i; } return sum; } console.log(sumToN(10)); // Output: 55

✅ Concepts Practiced: Looping with known bounds, accumulator pattern


πŸ” Exercise 2: Ask user until they type "yes" using while

javascript

code

let input = ""; while (input !== "yes") { input = prompt("Type 'yes' to continue:"); } console.log("Thank you!");

✅ Concepts Practiced: Condition checking, user interaction


πŸ” Exercise 3: Menu system using do...while

javascript

 code

let choice; do { choice = prompt("Choose an option:\n1. Say Hello\n2. Exit"); if (choice == "1") { console.log("Hello!"); } } while (choice !== "2"); console.log("Goodbye!");

✅ Concepts Practiced: User interaction, repeating menu


🎯  Tips

Use visual like flowcharts to explain loop flow








Emphasize when to use which loop – relate to scenarios.

Demonstrate infinite loop traps:

javascript

 code

while (true) { // dangerous if no break }

Show loop debugging using console.log.


πŸ› ️ Hands-On- Ideas


FizzBuzz Challenge using for:

javascript

 code

for (let i = 1; i <= 100; i++) { let output = ""; if (i % 3 === 0) output += "Fizz"; if (i % 5 === 0) output += "Buzz"; console.log(output || i); }

Reverse a string using while

javascript

code

let str = "hello", reversed = "", i = str.length - 1; while (i >= 0) { reversed += str[i]; i--; } console.log(reversed);

Input validation loop using do...while:

Ensure user enters a valid email or phone number format.


πŸ§‘‍🏫 Suggested  Flow

Introduction to loops

for loop deep dive (use sum, FizzBuzz)

while loop deep dive (unknown iterations)

do...while loop deep dive (menus, input validation)

Visual comparison

Practice tasks

Common errors & infinite loops

Live debugging demo


 Summary


Loop Type

Best Use Case

Executes At Least Once

for

Known number of iterations

No

while

Repeat until condition is false

No

do...while

Always run once, check after execution

Yes



πŸ“˜ Additional Resources

MDN Web Docs - Loops and Iteration

Eloquent JavaScript - Loops


No comments:

Post a Comment

“Unlock Hidden Power of Advanced Tables – Responsive Tricks That Shock Developers!”

  Module 38 : Responsive & Advanced Tables.  1. Introduction to Tables in Web Design Tables are used to display structured, relational d...