For Loops in JavaScript


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:

  • The 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 collection
  • The of keyword separates the loop variable from the collection we will iterate on
  • name is the collection to loop over

The 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.


Introduction

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.

Understanding the Basics

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:

The loop will print numbers from 0 to 4.

Main Concepts

Let's delve deeper into the key concepts of for loops:

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.

Examples and Use Cases

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.

Common Pitfalls and Best Practices

When using for loops, be mindful of the following common pitfalls:

Best practices:

Advanced Techniques

For loops can be combined with other programming constructs for more advanced use cases:

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).

Code Implementation

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!

Debugging and Testing

When debugging for loops, consider the following tips:

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");

Thinking and Problem-Solving Tips

When approaching problems involving for loops:

Conclusion

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.

Additional Resources