1var data = [1, 2, 3, 4, 5, 6];
2
3// traditional for loop
4for(let i=0; i<=data.length; i++) {
5 console.log(data[i]) // 1 2 3 4 5 6
6}
7
8// using for...of
9for(let i of data) {
10 console.log(i) // 1 2 3 4 5 6
11}
12
13// using for...in
14for(let i in data) {
15 console.log(i) // Prints indices for array elements
16 console.log(data[i]) // 1 2 3 4 5 6
17}
18
19// using forEach
20data.forEach((i) => {
21 console.log(i) // 1 2 3 4 5 6
22})
23// NOTE -> forEach method is about 95% slower than the traditional for loop
24
25// using map
26data.map((i) => {
27 console.log(i) // 1 2 3 4 5 6
28})
1const array1 = ['a', 'b', 'c'];
2
3array1.forEach(element => console.log(element));
1int[] numbers = {1,2,3,4,5};
2for (int i = 0; i < numbers.length; i++) {
3 System.out.println(i);
4}
1var array = ['Volvo','Bmw','etc'];
2for(var seeArray of array){
3 console.log(seeArray);
4}
1let exampleArray = [1,2,3,4,5]; // The array to be looped over
2
3// Using a for loop
4for(let i = 0; i < exampleArray.length; i++) {
5 console.log(exampleArray[i]); // 1 2 3 4 5
6}
7
1[1,2,3,4,"df"].forEach((value, index) => console.log(index,value));
2output
30 1
41 2
52 3
63 4
74 'df'