The for loop is one of the most commonly used looping structures in JavaScript. It allows you to execute a block of code a specific number of times, based on a condition.
It is typically used when you know beforehand how many times you need to iterate.
Table of Contents
Syntax of the for Loop
for (initialization; condition; finalExpression) { // Code to execute }
Explanation
initialization: Sets up a variable that will be used in the loop.
condition: The loop will continue to run as long as this expression is true.
finalExpression: Executes after each iteration of the loop; usually used to update the loop variable.
1. Basic for Loop Example
Let’s start with a simple example that prints numbers from 1 to 5.
for (let i = 1; i <= 5; i++) { console.log(i); }
Output:
1 2 3 4 5
Explanation
Initialization: let i = 1 sets up a loop variable i starting at 1.
Condition: i <= 5 ensures that the loop runs as long as i is less than or equal to 5.
Final Expression: i++ increments i by 1 after each iteration.
2. for Loop with Arrays
The for loop is often used to iterate over arrays.
let fruits = ['apple', 'banana', 'cherry']; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
Output:
apple banana cherry
Explanation
The loop runs from i = 0 to i < fruits.length (which is 3 in this case).
Each element of the array is accessed using fruits[i].
3. Using for Loop with break
You can use the break statement to exit the loop prematurely based on a specific condition.
for (let i = 1; i <= 10; i++) { if (i === 5) { break; // Exit the loop when i equals 5 } console.log(i); }
Output:
1 2 3 4
Explanation
The loop starts at i = 1 and increments i by 1 until it reaches 10.
When i equals 5, the break statement terminates the loop.
4. Using for Loop with continue
The continue statement skips the current iteration and moves to the next one.
for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); }
Output:
1 3 5 7 9
Explanation
The loop runs from i = 1 to i <= 10.
If i is even (i % 2 === 0), the continue statement skips printing that number.
5. Nested for Loops
You can use nested for loops to handle more complex tasks, such as printing a multiplication table.
for (let i = 1; i <= 5; i++) { for (let j = 1; j <= 5; j++) { console.log(`${i} * ${j} = ${i * j}`); } }
Output:
1 * 1 = 1 1 * 2 = 2 ... 5 * 4 = 20 5 * 5 = 25
Explanation
The outer loop iterates over i from 1 to 5.
The inner loop iterates over j from 1 to 5 for each i.
Each combination of i and j is printed as a product.
6. for Loop with Different Step Values
You can control how much the loop variable changes after each iteration. For example, you can decrement or increment by a different value.
for (let i = 10; i >= 0; i -= 2) { console.log(i); }
Output:
10 8 6 4 2 0
Explanation
The loop starts at i = 10 and decrements i by 2 (i -= 2) after each iteration.
The loop stops when i is less than 0.
7. Looping Over Objects Using for…in
The for…in loop is used to iterate over the properties of an object.
let person = { name: 'John', age: 25, city: 'New York' }; for (let key in person) { console.log(`${key}: ${person[key]}`); }
Output:
name: John age: 25 city: New York
Explanation
The loop iterates over each key in the person object.
person[key] is used to access the value of each property.
8. Looping Over Arrays Using for…of
The for…of loop is used to iterate over iterable objects like arrays and strings.
let colors = ['red', 'green', 'blue']; for (let color of colors) { console.log(color); }
Output:
red green blue
Explanation
The loop iterates directly over the elements of the colors array.
Each element is stored in the variable color and logged to the console.
9. for Loop with Conditions in Initialization and Final Expression
You can use more complex logic in the initialization and final expressions.
let start = 1, end = 20; for (; start <= end; start *= 2) { console.log(start); }
Output:
1 2 4 8 16
Explanation
The loop starts with start = 1.
Each time, start is multiplied by 2 (start *= 2).
The loop stops when start is greater than 20.
Conclusion
The for loop is a versatile looping structure in JavaScript. It is particularly useful when you know how many times you need to iterate or when working with arrays and objects.
Key Points to Remember
The for loop contains an initialization, a condition, and a final expression.
Use break to exit a loop early and continue to skip to the next iteration.
Nested for loops are great for multi-dimensional tasks.
Use for…in for iterating over object properties.
Use for…of for iterating over iterable items like arrays and strings.
With this tutorial, you should have a solid understanding of the for loop and its many use cases in JavaScript. Happy coding!