Edit Template
  • Home
  • /
  • Loops with Arrays
Edit Template
  • Home
  • /
  • Loops with Arrays

Loops with Arrays

When working with arrays in JavaScript, one of the most common tasks you’ll perform is going through each item—this is where loops become incredibly useful. Whether you want to display values, perform calculations, or transform data, iterating over arrays is essential.

Let’s take a look at some of the common looping techniques JavaScript provides for handling arrays.

Using the Traditional for Loop

The classic for loop gives you full control. You define a starting point, a stopping condition, and how the loop progresses. Here’s a simple example:

				
					let languages = ["HTML", "CSS", "JavaScript", "Python"];

for (let i = 0; i < languages.length; i++) {
  console.log("Learned:", languages[i]);
}

				
			

This loop starts at index 0 and continues until the end of the array. Each iteration prints out a language the user has “learned.”

Looping with forEach()

JavaScript arrays come with a built-in .forEach() method that allows you to run a function on every element. It’s a cleaner and more expressive approach.

				
					let skills = ["Problem Solving", "Debugging", "Design"];

skills.forEach(function(skill) {
  console.log("Skill:", skill);
});
console.log(data.length); // Output: 3

				
			

This loop calls the function for each element in the array—no need to worry about index tracking.

Iterating with for...of

The for...of loop is a modern and elegant way to access array values directly. It doesn’t give you the index but is perfect when you just care about the values.

				
					let tools = ["VS Code", "Chrome", "Git"];

for (let tool of tools) {
  console.log("Tool:", tool);
}

				
			

The loop automatically moves through each item, making your code neat and readable.

When to Use What?

  • If you need the index (for example, to modify elements or use a custom step), the traditional for loop is a solid choice.

  • If you just want to perform an action on each element and don’t need the index or to break out of the loop early, forEach() is ideal.

  • If your focus is only on the values and you want simplicity, go with for.

A Word of Caution

When modifying an array while looping through it, especially adding or removing elements, use a for loop. This lets you control the behavior safely without unexpected results.

				
					let nums = [1, 2, 3, 4, 5];

for (let i = 0; i < nums.length; i++) {
  if (nums[i] === 3) {
    nums.splice(i, 1); // removes 3
  }
}
console.log(nums); // [1, 2, 4, 5]

				
			

Modifying arrays inside forEach() can be risky as it doesn’t respond well to changes in the array during iteration.

Wrap-up

Loops allow you to interact with arrays in powerful ways. From classic for loops to modern for...of, JavaScript gives you multiple tools to handle collections with ease. Experiment with each to find what fits best for your task.

Scroll to Top