forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 7
JavaScript looping arrays
Ramesh Fadatare edited this page Aug 11, 2020
·
1 revision
The example shows four ways of looping over a JavaScript array.
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++;
}