javascript for loop

JavaScript: for Loop

The for loop in JavaScript is a powerful tool that lets you repeat a block of code multiple times. You use it when you know exactly how many times you want something to happen. For example, if you want to print numbers from 1 to 5, or go through all items in a list, a for loop makes that easy.

It’s like telling the computer, “Do this task again and again, but only this many times.”

In this article, we’ll explore how to use the for loop to repeat tasks, work with arrays, and more. By the end, you’ll know how to use it for all kinds of repeating actions in your code.

Basic Syntax of the for Loop

The for loop has three main parts that control how it runs:

for (initialization; condition; final expression) {
  // Code to run
}

Initialization is where you set up a starting point. Usually, you create a variable like let i = 0. Condition is checked before each loop run. If it’s true, the loop runs. If it’s false, the loop stops. Final expression runs after every loop run. Usually, it updates your variable, like i++.

Here’s an example:

for (let i = 0; i < 3; i++) {
  console.log(i);
}
// Output: 0, 1, 2

This loop starts at i = 0, checks if i < 3, runs the code, then adds 1 to i after each run. It stops when i reaches 3.

Simple Counting with for

You can use a for loop to count numbers in order. Here’s how to count from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// Output: 1, 2, 3, 4, 5

In this example:

  • It starts with i = 1.
  • Before each run, it checks i <= 5. If true, it runs the code.
  • After each run, it increases i by 1 (i++).
  • When i becomes 6, the condition i <= 5 is false, so the loop stops.

This is a basic way to repeat something a fixed number of times.

Counting Down with for

You can also use a for loop to count backward. This is helpful for countdowns or going through items in reverse.

Here’s an example of counting down from 5 to 1:

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
// Output: 5, 4, 3, 2, 1

In this example:

  • It starts with i = 5.
  • Before each loop, it checks i >= 1.
  • After each run, it subtracts 1 from i (i--).
  • When i becomes 0, the condition is false, so the loop ends.

This pattern is great for any task that needs to go in reverse order.

Using for with Arrays

The for loop is perfect for going through arrays by using index numbers. You can use it to access each item one by one.

Here’s an example:

const fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output: apple, banana, cherry

In this example:

  • i starts at 0 (the first item).
  • The loop runs while i is less than fruits.length (which is 3).
  • Each time, it prints fruits[i].
  • i increases by 1 after each loop until it reaches 3.

This is one of the most common ways to go through arrays in JavaScript.

Skipping Steps with continue

The continue statement lets you skip the current step in a loop and move on to the next one. This is helpful when you want to ignore certain items.

Example: Skip even numbers in a loop

for (let i = 1; i <= 5; i++) {

  if (i % 2 === 0) continue;
  console.log(i);

}
// Output: 1, 3, 5

In this example:

  • The loop counts from 1 to 5.
  • If a number is even (i % 2 === 0), continue skips the console.log(i) and goes to the next number.
  • Only the odd numbers get printed.

This is a simple way to skip certain values based on a condition.

Stopping a Loop Early with break

The break statement allows you to exit a loop early when a certain condition is met. This is useful if you no longer need to continue looping after a specific point.

Example: Stop when a number reaches a certain value

for (let i = 1; i <= 5; i++) {

  if (i === 4) break;
  console.log(i);

}
// Output: 1, 2, 3

In this example:

  • The loop starts counting from 1 to 5.
  • When i reaches 4, the if condition (i === 4) becomes true, and the break statement is executed.
  • This causes the loop to stop immediately, so the numbers 4 and 5 are not printed.

Using break is a quick way to stop a loop as soon as a specific condition is met.

Nested for Loops

A nested for loop is when you place one for loop inside another. This allows you to perform tasks like working with multi-dimensional arrays or creating patterns like grids.

Example: Multiplication table

for (let i = 1; i <= 5; i++) {

  let row = '';

  for (let j = 1; j <= 5; j++) {
    row += (i * j + ' ').padStart(3);
  }

  console.log(row);

}

In this example, we print a multiplication table – the outer loop runs from 1 to 5. For each value of i, the inner loop also runs from 1 to 5.

This is perfect for creating grids, like for games or UI elements. Performing operations on multi-dimensional data, such as matrices or 2D arrays.

Using for with Strings

You can use a for loop to iterate over each character in a string by accessing its index. Strings are essentially arrays of characters, so the for loop can be used to loop through them just like arrays.

Example: Print each letter in a word

const word = "JavaScript";

for (let i = 0; i < word.length; i++) {
  console.log(word[i]);
}

The loop starts at index 0 and continues until i is less than the length of the string. In each iteration, it accesses the character at the current index i using word[i] and prints it.

This approach is ideal for processing each character in a string, such as checking for certain letters or formatting text. And breaking down a string into its components, like extracting individual letters or searching for substrings.

Using for with Objects via Object.keys()

When you want to loop over an object’s properties (keys), you can’t directly use a for loop like you would with arrays. Instead, you can use Object.keys() to get an array of the object’s property names, and then loop through this array to access both the keys and their corresponding values.

const person = { name: "Edward", age: 30 };
const keys = Object.keys(person);

for (let i = 0; i < keys.length; i++) {
  console.log(keys[i], person[keys[i]]);
}

In this example:

  • Object.keys(person) creates an array of the keys: ["name", "age"].
  • The for loop then iterates over this array of keys.
  • For each key, the loop accesses the value in the person object by using person[keys[i]].

This method is useful when you need to loop over an object’s properties and access both the property name (key) and its value. It can also be used to dynamically process object data, such as when handling configurations or user data.

Modifying Array Elements in a for Loop

The for loop allows you to modify the values of array elements while iterating through the array. By using the array index, you can directly update the values as the loop runs.

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i] * 2; // Multiply each element by 2
}

console.log(numbers);

In this example:

  • The for loop iterates over each element in the numbers array using the index i.
  • Inside the loop, we modify the array element by multiplying the value at numbers[i] by 2.
  • After the loop finishes, the array will contain the updated values.

This method is commonly used when you need to apply a transformation to each item in an array, such as multiplying numbers, changing text case, or adjusting data for display. Modifying array elements within a for loop gives you fine-grained control over the data and allows complex manipulations.

Looping a Fixed Number of Times Without Arrays

Sometimes, you may need to repeat a task a fixed number of times, without needing to work with an array. The for loop is perfect for this, as you can simply specify how many times the loop should run.

for (let i = 0; i < 3; i++) {
  console.log("Hello");
}

The loop runs 3 times because the condition i < 3 ensures it stops after the third iteration. Each time the loop runs, it prints "Hello" to the console.

This approach is ideal for tasks like repeating a simple action, such as logging a message multiple times, displaying a prompt a certain number of times, or running a process a set number of times. You don’t need to deal with any arrays or objects—just a straightforward repeat of tasks for a specific count.

Using Variables Inside the Loop Block

In a for loop, you can create and use variables inside the loop block. These variables can be used to perform tasks or calculations for each iteration. However, they do not affect the code outside of the loop, as their scope is limited to the loop.

for (let i = 0; i < 3; i++) {
  let square = i * i;  // Variable inside the loop
  console.log("Square of", i, "is", square);
}

console.log(i); // This will cause an error because 'i' is not accessible outside the loop

Inside the loop, we create a variable square that calculates the square of i. Each time the loop runs, square is printed along with the current value of i.

The variable square is created on each iteration and holds the square of the current i. It’s used only within the loop, and each time the loop runs, it’s re-calculated. The console.log(i) after the loop results in an error because the let i declared inside the loop has a block scope and is not accessible outside of it.

This shows that loop variables like i and square are contained within the loop, preventing them from interfering with the rest of the code.

Conclusion

To wrap up, the for loop is a powerful tool in JavaScript that allows you to repeat tasks efficiently. Whether you’re counting numbers, looping through arrays, or working with strings, the for loop helps you automate repetitive tasks.

By experimenting with different setups like counting up or down, modifying array elements, and nesting loops, you can tackle a wide range of coding challenges.

The for loop is one of the most flexible tools for repeating code in JavaScript, and mastering it will make your coding tasks much easier and more efficient.

Scroll to Top