Welcome Guys, My name is Md Taqui Imam i am a Full Stack developer
And in Today post i will tell you about JavaScript Loops.
Loops are super important in JavaScript.
This blog will show you 13 cool looping patterns
in a way that even a beginner can even understand. By the end you'll be looping like a pro!
So, Let's Begin , and Don't Forget to:
Startπ
π Count to 10
A basic counting loop:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
π Drive in Reverse
Count backwards from 10 to 1:
for (let i = 10; i >= 1; i--) {
console.log(i);
}
π Pick Fruit from a Basket
Loop through an array of fruits:
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
π₯ Make Pancakes
Nested loop to make a 5x5 pancake grid:
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(i, j);
}
}
πββοΈ Keep Running Until Tired
While loop that runs 5 times:
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
πΆ March Once Before Checking
Do-while loop that always runs 1 time:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
π Skip 3
Continue on iteration 3 of a for loop:
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}
π Stop at 3
Break out of a loop when i equals 3:
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i);
}
π€Ή Juggle Numbers
Sum all items in an array:
const nums = [1, 2, 3];
let total = 0;
for (let i = 0; i < nums.length; i++) {
total += nums[i];
}
console.log(total);
π§βπ« Teacher's Assistant
Loop through object properties:
const teacher = {
name: 'James',
age: 30
};
for (let prop in teacher) {
console.log(prop);
}
π€Έ Flip and Flop
Loop backwards and forwards:
for (let i = 10; i >= 0; i--) {
console.log(i);
}
for (let i = 0; i <= 10; i++) {
console.log(i);
}
π₯ Pancake Bonanza
Reusable pancake making function:
function makePancakes() {
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
console.log(i, j);
}
}
}
makePancakes();
π€ΈββοΈ Looping Gymnastics
Recursion:
function countDown(num) {
if (num < 0) return;
console.log(num);
countDown(num - 1);
}
countDown(5);
π Keep Practicing Loops!
The more you practice different looping patterns the better you'll get. Soon you'll be an expert loop master!
I hope you like this Blog Post, please drop a Like ππ₯π¦
And Comment if you have any doubt.
Top comments (3)
Taqui, you seem to always be doing something fun. It's very cute. I'm glad you're hitting multiple levels of experience on this site. Keep-a-going!
Thank you so much, Jo! π
I really enjoy being part of this community and sharing insights.
Your encouragement means a lot! ** I'll definitely keep it up. π**
Yeah, buddy =)~