© Yogesh Suryawanshi
© Yogesh Suryawanshi
© Yogesh Suryawanshi
© Yogesh Suryawanshi

Understanding Loops

Learn different types of loops in JavaScript with visual examples.

रोजच्या जीवनातील उदाहरणे (Real Life Examples in Marathi)

1. सकाळी व्यायाम (For Loop)

// दहा सूर्यनमस्कार for (let नमस्कार = 1; नमस्कार <= 10; नमस्कार++) { console.log(`सूर्यनमस्कार क्रमांक ${नमस्कार} पूर्ण! 🧘‍♂️`); }

2. चहा पिणे (While Loop)

let चहाचीघोट = 5; while (चहाचीघोट > 0) { console.log(`अजून ${चहाचीघोट} घोट बाकी आहेत ☕`); चहाचीघोट = चहाचीघोट - 1; }

3. वर्गातील विद्यार्थी (forEach)

let विद्यार्थी = ['राम', 'श्याम', 'सीता', 'गीता']; विद्यार्थी.forEach((नाव) => { console.log(`${नाव} उपस्थित आहे ✋`); });

1. Simple For Loop

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

2. While Loop

// Double a number until it's over 100 let num = 2; while (num <= 100) { console.log(num); num = num * 2; }

3. forEach with Array

// Loop through array of fruits const fruits = ['Apple', 'Banana', 'Orange']; fruits.forEach((fruit, index) => { console.log(`${index + 1}: ${fruit}`); });

4. Multiplication Table

// Create multiplication table for (let i = 1; i <= 5; i++) { for (let j = 1; j <= 5; j++) { console.log(`${i} × ${j} = ${i*j}`); } }

Loop Types and Syntax

For Loop Syntax

for (initialization; condition; increment/decrement) { // code to be executed } // Example: for (let i = 0; i < 5; i++) { console.log(i); }

While Loop Syntax

while (condition) { // code to be executed } // Example: let count = 0; while (count < 5) { console.log(count); count++; }

forEach Loop Syntax

array.forEach((item, index, array) => { // code to be executed }); // Example: const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num));

Practice Exercises

Exercise 1: Number Sum

Write a loop that calculates the sum of numbers from 1 to n:

// Your solution here let n = 5; let sum = 0; for (let i = 1; i <= n; i++) { sum += i; } console.log(`Sum of numbers from 1 to ${n} is ${sum}`);

Exercise 2: Array Transformation

Write a forEach loop that doubles each number in an array:

// Your solution here const numbers = [1, 2, 3, 4, 5]; const doubled = []; numbers.forEach(num => { doubled.push(num * 2); }); console.log(`Original: ${numbers}`); console.log(`Doubled: ${doubled}`);
Design and developed by Yogesh Suryawanshi 📞 +91 957 926 3798