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})
1//function arrayLooper will loop through the planets array
2const planets = ["Mercury", "Venus", "Earth", "Mars"];
3
4const arrayLooper = (array) => {
5 for (let i = 0; i < array.length; i++) {
6 console.log(array[i]);
7 }
8};
9arrayLooper(planets);
1let fruits = ['Apple', 'Banana'];
2
3fruits.forEach(function(item, index, array) {
4 console.log(item, index);
5});
6// Apple 0
7// Banana 1
1fruits.forEach(function(item, index, array) {
2 console.log(item, index)
3})
4// Apple 0
5// Banana 1
6
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