Iterating over an array in JavaScript

In Java, a for loop can be used to go through elements in an array like this:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Execute some code
}

Is it possible to achieve the equivalent in JavaScript?

To iterate over an array in JavaScript similar to Java’s enhanced for loop, you can use the for...of loop. It’s straightforward and easy to use:

const myStringArray = ["Hello", "World"];

// Loop through each element in the array
for (const s of myStringArray) {
  console.log(s);
  // Execute some code with each element
}

This for...of loop efficiently goes through each item in the array, allowing you to perform actions on them without adding extra complexity to your code.

2 Likes