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})
1var colors = ["red","blue","green"];
2for (var i = 0; i < colors.length; i++) {
3 console.log(colors[i]);
4}
1var colors = ["red","blue","green"];
2colors.forEach(function(color) {
3 console.log(color);
4});
1const myArray = ['foo', 'bar'];
2
3myArray.forEach(x => console.log(x));
4
5//or
6
7for(let i = 0; i < myArray.length; i++) {
8 console.log(myArray[i]);
9}
10
1var myStringArray = ["hey","World"];
2var arrayLength = myStringArray.length;
3for (var i = 0; i < arrayLength; i++) {
4 console.log(myStringArray[i]);
5 //Do something
6}
1const numbers = [1, 2, 3, 4]
2numbers.forEach(number => {
3 console.log(number);
4}
5
6for (let i = 0; i < number.length; i++) {
7 console.log(numbers[i]);
8}
1let array = ['Item 1', 'Item 2', 'Item 3'];
2
3for (let item of array) {
4 console.log(item);
5}
1let my_array = [1, 2, 3, 4, 5];
2
3// standard for loop
4for(let i = 0; i < my_array.length; i++) {
5 console.log(my_array[i]) // 1 2 3 4 5 6
6}
7
8// for and of method
9for(let i of my_array) {
10 console.log(i)
11}
12
13/*
14Results:
151 2 3 4 5
161 2 3 4 5
17(From both methods)
18*/
1const array1 = ['a', 'b', 'c'];
2
3array1.forEach(element => console.log(element));