A for loop is a special type of loop in JavaScript which allows us to loop over the items of a collection, such as a string or an array.
Looping through a string:
For example, a string is a sequence of characters, so we can use a for loop to iterate over each character and do something with that character:
let name = "Andy";
for(let letter of name) {
console.log(letter);
}
Let's break down this code:
for
keyword that indicates the start of a for
loop.letter
is the loop variable. It will take the value of each different item in the collectionof
keyword separates the loop variable from the collection we will iterate onname
is the collection to loop overThe output of this code is:
A
n
d
y
As you can see, on each iteration, letter
was assigned the value of the next item in the string and inside the loop, we printed that value.
Looping through an array:
We can also use for loops with lists:
let fruits = ["banana", "orange", "pear", "kivi"];
for (let fruit of fruits) {
console.log("I eat " + fruit);
}
The output of this code is:
I eat banana
I eat orange
I eat pear
I eat kivi
Assignment
Now let's greet our friends 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. For loops are a fundamental part of programming that allow us to repeat a block of code multiple times. They are particularly useful for iterating over collections such as arrays and strings. Understanding for loops is crucial for tasks like data processing, automation, and repetitive operations.
A for loop in JavaScript consists of three main parts: the initialization, the condition, and the increment/decrement. These parts control the loop's execution and determine how many times the loop will run.
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example:
let i = 0;
initializes the loop variable i
to 0.i < 5;
is the condition that keeps the loop running as long as i
is less than 5.i++
increments the loop variable i
by 1 after each iteration.The loop will print numbers from 0 to 4.
Let's delve deeper into the key concepts of for loops:
true
, the loop continues; otherwise, it stops.Here's an example of a for loop that iterates over an array:
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This loop will print each fruit in the array.
For loops are versatile and can be used in various scenarios:
Example: Summing the elements of an array:
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum:", sum);
This code calculates the sum of all elements in the numbers
array.
When using for loops, be mindful of the following common pitfalls:
Best practices:
for...of
or forEach
for cleaner syntax when iterating over arrays.For loops can be combined with other programming constructs for more advanced use cases:
break
to exit a loop early or continue
to skip the current iteration.Example of a nested loop:
let 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]);
}
}
This code prints each element of a 2D array (matrix).
Let's implement a for loop to greet a list of friends:
let friends = ["Alice", "Bob", "Charlie"];
for (let friend of friends) {
console.log("Hello, " + friend + "!");
}
This code will output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
When debugging for loops, consider the following tips:
console.log
to print loop variables and track their values.Example of a test case for a function using a for loop:
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// Test case
let testArray = [1, 2, 3, 4, 5];
console.assert(sumArray(testArray) === 15, "Test case failed");
When approaching problems involving for loops:
In this lesson, we covered the basics and advanced concepts of for loops in JavaScript. Mastering for loops is essential for efficient and effective programming. Practice regularly and explore different use cases to deepen your understanding.
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE