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}
1let array = ["loop", "this", "array"]; // input array variable
2for (let i = 0; i < array.length; i++) { // iteration over input
3 console.log(array[i]); // logs the elements from the current input
4}
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*/
1var arr = [10, 9, 8, 7, 6];
2for (var i = 0; i < arr.length; i++) {
3 console.log(arr[i]);
4}
1array iteration styles illustrate programming paradigms
2let newArray = []; const theArray = [2, 4, 6, 8, 10]
3// 1) imperative, explicit
4for (var i = 0; i < theArray.length; i++) { // var is mutable
5 console.log(theArray[i]); // side effect from writing to console
6 newArray[i] = theArray[i] * theArray[i] // let is mutable
7}
8// 2) forEach function of the Array class TIP: console.log(Array) //Does not change the array, Returns undefined
9function f1(theValue, theIndex, originalArray) { numVal = numVal * theValue }
10theArray.forEach(f1); console.log( ` creates ${ newArray }` );
11run.addEventListener("click", function () {cpeople.forEach((element) => console.log(element.firstname));});
12// 3) declarative, implicit
13function f1(v,i,a) { v=v*v }
14const constArray = theArray.map(fNumbers);
15console.log( ` immutable ${ newArray }` );
16
17
18
19