JavaScript Loops Kya Hote Hain?
Code ko Baar Baar Execute Karne ka Efficient Tarika Sikhein.
Introduction to Loops
JavaScript me loops ka use kisi bhi task ko repeat karne ke liye kiya jata hai. Agar hume ek hi code ko multiple times execute karna ho, to loops ka use bahut helpful hota hai. Yeh code ko concise aur maintainable banata hai. JavaScript me different types ke loops hote hain jo alag-alag situations ke liye use kiye jate hain.
1. The for
Loop
for
loop ek control flow statement hai jo ek block of code ko ek fixed number of times execute karne ke liye use hota hai. Yeh loop initialization, condition, aur increment/decrement ke sath kaam karta hai.
for (let i = 1; i <= 5; i++) {
console.log("Number: " + i);
}
2. The while
Loop
while
loop ek condition ke true
hone tak continuously execute hota rehta hai. Yeh tab useful hota hai jab hume pehle se nahi pata hota ki kitni baar loop chalana hai.
let i = 1;
while (i <= 5) {
console.log("Count: " + i);
i++;
}
3. The do-while
Loop
Yeh loop while
loop jaisa hi hai, lekin isme code block kam se kam ek baar zaroor execute hota hai, chahe condition false hi kyu na ho.
let i = 1;
do {
console.log("Value: " + i);
i++;
} while (i <= 5);
4. The for...in
Loop
for...in
loop ka use object ki properties ko iterate karne ke liye hota hai. Yeh har iteration me property ka naam (key) return karta hai.
const student = { name: "Rahul", age: 20, city: "Delhi" };
for (let key in student) {
console.log(key + ": " + student[key]);
}
// Output:
// name: Rahul
// age: 20
// city: Delhi
5. The for...of
Loop
for...of
loop (ES6 me introduce hua) iterable objects (jaise Arrays, Strings, Maps) ki values ko iterate karne ke liye use hota hai.
const numbers = [10, 20, 30, 40];
for (let num of numbers) {
console.log(num);
}
// Output: 10, 20, 30, 40
6. The forEach()
Method
Yeh arrays ka ek special method hai jo array ke har element ke liye ek function run karta hai.
const fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
// Output:
// 0: Apple
// 1: Banana
// 2: Mango
Loops ka Sahi Use Kab Karein?
Loop Type | Best Use Case |
---|---|
for | Jab iterations ka number pata ho (e.g., 1 to 10). |
while | Jab iterations ka number nahi pata ho, sirf condition pata ho. |
do-while | Jab code ko kam se kam ek baar run karna zaroori ho. |
for...in | Object ki properties ko iterate karne ke liye. |
for...of | Arrays ya doosre iterables ki values ko iterate karne ke liye. |
forEach() | Array ke har element par ek operation perform karne ke liye. |
Key Takeaways
- Loops code ko repeat karne ka ek efficient tarika hai.
for
loop fixed iterations ke liye best hai.while
loop condition-based execution ke liye best hai.for...of
arrays ki values ke liye aurfor...in
objects ki keys ke liye use hota hai.
Ek `for` loop ka use karke 1 se 10 tak ke numbers ka table print karein.
Practice in JS EditorApni knowledge test karne ke liye is quick quiz ko dein.
Start Quiz