We can achieve many different outcomes with for loops.
It's all about tuning the initialization
, condition
and iteration
statements.
For example, we can print all numbers from 2
through 6
:
for (let i = 2; i < 7; i++) {
console.log(i);
}
The output of this code is:
2
3
4
5
6
Let's break down this code:
The initialization statement is let i = 2
, so we start iterating from number 2.
The condition statement is i < 7
. We could've written i <= 6
and it would still be correct.
The iteration statement is i++
, so we increase our number by 1 every time.
Assignment
Let's print all numbers from 3
through 10
using a for loop.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of for loops in JavaScript, a fundamental control structure used to repeat a block of code a certain number of times. Understanding for loops is crucial for tasks that require iteration, such as processing arrays, generating sequences, and automating repetitive tasks.
For loops are particularly useful in scenarios where you need to execute a block of code multiple times with a varying value, such as iterating over a list of items or performing a calculation a set number of times.
A for loop in JavaScript consists of three main parts:
Here is a simple example to illustrate these concepts:
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example:
let i = 0
, so the loop starts with i
equal to 0.i < 5
, so the loop will run as long as i
is less than 5.i++
, which increments i
by 1 after each iteration.Let's apply these concepts to solve the assignment of printing numbers from 3 through 10:
for (let i = 3; i <= 10; i++) {
console.log(i);
}
Breaking down this code:
let i = 3
- We start iterating from number 3.i <= 10
- The loop will run as long as i
is less than or equal to 10.i++
- We increase i
by 1 after each iteration.Here are a few more examples to demonstrate the versatility of for loops:
Example 1: Printing even numbers from 2 to 10
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
Example 2: Printing numbers in reverse from 10 to 1
for (let i = 10; i > 0; i--) {
console.log(i);
}
These examples show how you can adjust the initialization, condition, and iteration statements to achieve different outcomes.
When working with for loops, it's important to avoid common mistakes such as:
Best practices for writing clear and efficient for loops include:
For more advanced use cases, you can nest for loops to handle multi-dimensional arrays or perform complex iterations:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
This example demonstrates a nested for loop, which iterates over a 3x3 grid.
Let's revisit the assignment and implement the solution:
for (let i = 3; i <= 10; i++) {
console.log(i);
}
This code will print all numbers from 3 to 10, inclusive.
When debugging for loops, consider the following tips:
console.log
statements to track the value of the loop variable at each iteration.To test your for loops, you can write test cases that verify the output for different ranges and conditions:
function testPrintNumbers() {
let result = [];
for (let i = 3; i <= 10; i++) {
result.push(i);
}
console.assert(JSON.stringify(result) === JSON.stringify([3, 4, 5, 6, 7, 8, 9, 10]), 'Test failed');
}
testPrintNumbers();
When approaching problems that require for loops:
In this lesson, we covered the basics of for loops in JavaScript, including their structure, common use cases, and best practices. Mastering for loops is essential for writing efficient and effective code, especially when dealing with repetitive tasks and iterations.
We encourage you to practice writing for loops with different conditions and ranges to solidify your understanding and explore further applications.
For further reading and practice, consider the following resources: