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(`${नाव} उपस्थित आहे ✋`);
});
3. forEach with Array
// Loop through array of fruits
const fruits = ['Apple', 'Banana', 'Orange'];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}: ${fruit}`);
});
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}`);