For Loops in Javascript
Learn about forloop in javascript with practical examples and code snippets.
Traditional for Loop
Basic for loop.
Code
const cars = [ { id: 1, name: "Nexon", brand: "Tata", make: "2017", rating: 2 }, { id: 2, name: "Verna", brand: "Hyundai", make: "2008", rating: 4 }, { id: 3, name: "Bolero", brand: "Mahindra", make: "2012", rating: 5 }, { id: 4, name: "Baleno", brand: "Maruti", make: "2022", rating: 4 }, { id: 5, name: "Seltos", brand: "Kia", make: "2011", rating: 3 }, { id: 6, name: "G-class", brand: "Mercedes", make: "2024", rating: 5 } ]; for (let i = 0; i < cars.length; i++) { console.log(`${cars[i].brand} -> ${cars[i].name}`); }
for...of Loop (ES6)
Iterates over iterable objects (arrays, strings, etc.
) With index using entries().
Code
for (const car of cars) { console.log(`${car.brand} -> ${car.name}`); } for (const [index, car] of cars.entries()) { console.log(`${index}: ${car.name}`); }
for...in Loop
Iterates over object properties (keys) ⚠️ Use with caution on arrays - iterates over indices as strings Better for objects.
Code
for (const index in cars) { console.log(`${index}: ${cars[index].name}`); } const person = { name: "Kuldeep", age: 25, city: "Mumbai" }; for (const key in person) { console.log(`${key}: ${person[key]}`); }
forEach Method
Array method - executes function for each element forEach with this context.
Code
cars.forEach((car, index) => { console.log(`${index}: ${car.brand} -> ${car.name}`); }); const counter = { count: 0, increment: function(items) { items.forEach(function(item) { this.count++; }, this); // Pass 'this' as second argument } };
Loop Control (break, continue)
break - exit loop completely continue - skip to next iteration.
Code
for (let i = 0; i < cars.length; i++) { if (cars[i].rating === 5) { console.log(`Found perfect car: ${cars[i].name}`); break; // Exit loop } } for (let i = 0; i < cars.length; i++) { if (cars[i].rating < 4) { continue; // Skip this iteration } console.log(`High rated: ${cars[i].name}`); }
Nested Loops
Code
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`); } }
Reverse Loop
Loop backwards.
Code
for (let i = cars.length - 1; i >= 0; i--) { console.log(cars[i].name); }
Loop with Step
Skip elements (every 2nd element).
Code
for (let i = 0; i < cars.length; i += 2) { console.log(cars[i].name); }
Performance Considerations
Cache array length for better performance Process cars[i] Modern for.
of is optimized.
Code
const length = cars.length; for (let i = 0; i < length; i++) { } for (const car of cars) { }
Common Patterns
Find first matching element Collect matching elements Transform elements When to Use Which Loop.
for loop - When you need index or control flow for.
of - Modern, clean, for arrays for.
in - For object properties forEach - Functional style, can't break.
Code
let foundCar = null; for (const car of cars) { if (car.rating === 5) { foundCar = car; break; } } const highRatedCars = []; for (const car of cars) { if (car.rating >= 4) { highRatedCars.push(car); } } const carNames = []; for (const car of cars) { carNames.push(car.name); } for (let i = 0; i < cars.length; i++) { if (i === 2) break; // Can break/continue easily } for (const car of cars) { console.log(car.name); } for (const key in person) { console.log(key, person[key]); } cars.forEach(car => console.log(car.name));
Right-Aligned Pyramid
Add spaces for right alignment Add stars Output:.
Code
function printPyramid(rows) { for (let i = 0; i < rows; i++) { let pattern = ''; for (let j = 0; j < rows - i - 1; j++) { pattern += ' '; } for (let k = 0; k <= i; k++) { pattern += '* '; } console.log(pattern); } } printPyramid(5);
Left-Aligned Pyramid
Output:
Code
function printLeftPyramid(rows) { for (let i = 0; i < rows; i++) { let pattern = ''; for (let j = 0; j <= i; j++) { pattern += '* '; } console.log(pattern); } } printLeftPyramid(5);
Inverted Pyramid
Add spaces Add stars Output:.
Code
function printInvertedPyramid(rows) { for (let i = rows; i > 0; i--) { let pattern = ''; for (let j = 0; j < rows - i; j++) { pattern += ' '; } for (let k = 0; k < i; k++) { pattern += '* '; } console.log(pattern); } } printInvertedPyramid(5);
Number Pyramid
Add spaces Add numbers Output: 1 2 3 4 1 2 3 4 5.
Code
function printNumberPyramid(rows) { for (let i = 1; i <= rows; i++) { let pattern = ''; for (let j = 0; j < rows - i; j++) { pattern += ' '; } for (let k = 1; k <= i; k++) { pattern += k + ' '; } console.log(pattern); } } printNumberPyramid(5);
Diamond Pattern
Upper half Lower half Output:.
Code
function printDiamond(rows) { for (let i = 0; i < rows; i++) { let pattern = ''; for (let j = 0; j < rows - i - 1; j++) { pattern += ' '; } for (let k = 0; k <= i; k++) { pattern += '* '; } console.log(pattern); } for (let i = rows - 2; i >= 0; i--) { let pattern = ''; for (let j = 0; j < rows - i - 1; j++) { pattern += ' '; } for (let k = 0; k <= i; k++) { pattern += '* '; } console.log(pattern); } } printDiamond(5);
Hollow Pyramid
Add spaces Add stars (hollow inside) Output:.
Code
function printHollowPyramid(rows) { for (let i = 0; i < rows; i++) { let pattern = ''; for (let j = 0; j < rows - i - 1; j++) { pattern += ' '; } for (let k = 0; k <= i; k++) { if (k === 0 || k === i || i === rows - 1) { pattern += '* '; } else { pattern += ' '; } } console.log(pattern); } } printHollowPyramid(5);
Character Pyramid
Add spaces Add characters Output: A B C D A B C D E.
Code
function printCharPyramid(rows, char = 'A') { for (let i = 0; i < rows; i++) { let pattern = ''; for (let j = 0; j < rows - i - 1; j++) { pattern += ' '; } for (let k = 0; k <= i; k++) { pattern += String.fromCharCode(char.charCodeAt(0) + k) + ' '; } console.log(pattern); } } printCharPyramid(5, 'A');
Summary
Understanding forloop is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- forloop is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding forloop will help you in technical interviews