Q:

javascript code to loop through array

let array = ['Item 1', 'Item 2', 'Item 3'];

// Here's 4 different ways
for (let index = 0; index < array.length; index++) {
  console.log(array[index]);
}

for (let index in array) {
  console.log(array[index]);
}

for (let value of array) {
  console.log(value); // Will log value in array
}

array.forEach((value, index) => {
  console.log(index); // Will log each index
  console.log(value); // Will log each value
});
7
const myArray = ['foo', 'bar'];

myArray.forEach(x => console.log(x));

//or

for(let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}
5
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}
27
var myStringArray = ["hey","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}
12
var colors = ["red","blue","green"];
colors.forEach(function(color) {
  console.log(color);
});
11
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));
20
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}
9
let array = ['Item 1', 'Item 2', 'Item 3'];

for (let item of array) {
  console.log(item);
}
5
array iteration styles illustrate programming paradigms
let newArray = [];  const theArray = [2, 4, 6, 8, 10]
// 1) imperative, explicit
for (var i = 0; i < theArray.length; i++) {  // var is mutable
    console.log(theArray[i]);                // side effect from writing to console
	newArray[i] = theArray[i] * theArray[i]  // let is mutable
}
// 2) forEach function of the Array class TIP: console.log(Array) //Does not change the array, Returns undefined
function f1(theValue, theIndex, originalArray) { numVal = numVal *  theValue }
theArray.forEach(f1);   console.log( ` creates  ${   newArray   }` );
run.addEventListener("click", function () {cpeople.forEach((element) => console.log(element.firstname));});
// 3) declarative, implicit 
function f1(v,i,a) { v=v*v }
const constArray = theArray.map(fNumbers); 
console.log( ` immutable  ${ newArray }` );



1

New to Communities?

Join the community