The example shows four ways of looping over a JavaScript array.
Check out all 100 + JavaScript Examples
Check out all JavaScript programs at All JavaScript Programs
JavaScript looping arrays
const words = ["pen", "pencil", "rock", "sky", "earth"];
words.forEach(e => console.log(e));
for (let word of words) {
console.log(word);
}
for (let idx in words) {
console.log(words[idx]);
}
const len = words.length;
for (let i = 0; i < len; i++) {
console.log(words[i]);
}
const i = 0;
while (i < len) {
console.log(words[i]);
i++;
}
We use the forEach() method to traverse the array. It executes the provided function once for each array element:
words.forEach(e => console.log(e));
With for of loop, we go over the values of the array:
for (let word of words) {
console.log(word);
}
With for in loop, we go over the indexes of the array:
for (let idx in words) {
console.log(words[idx]);
}
Here we use the C-like for loop to traverse the array:
var len = words.length;
for (let i = 0; i < len; i++) {
console.log(words[i]);
}
var i = 0;
while (i < len) {
console.log(words[i]);
i++;
}
Check out all 100 + JavaScript Examples
Check out all JavaScript programs at All JavaScript Programs