javascript loop through list code example

Example 1: javascript loop through array

var data = [1, 2, 3, 4, 5, 6];

// traditional for loop
for(let i=0; i<=data.length; i++) {
  console.log(data[i])  // 1 2 3 4 5 6
}

// using for...of
for(let i of data) {
	console.log(i) // 1 2 3 4 5 6
}

// using for...in
for(let i in data) {
  	console.log(i) // Prints indices for array elements
	console.log(data[i]) // 1 2 3 4 5 6
}

// using forEach
data.forEach((i) => {
  console.log(i) // 1 2 3 4 5 6
})
// NOTE ->  forEach method is about 95% slower than the traditional for loop

// using map
data.map((i) => {
  console.log(i) // 1 2 3 4 5 6
})

Example 2: javascript loop through array

var colors = ["red","blue","green"];
colors.forEach(function(color) {
  console.log(color);
});

Example 3: loop through javascript array

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Example 4: loop through array javascript

/* ES6 */
const cities = ["Chicago", "New York", "Los Angeles"];
cities.map(city => {
	console.log(city)
})

Example 5: javascript iterate through for loop

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

Example 6: javascript loop through array

var numbers = [1, 2, 3, 4, 5];
numbers.forEach((Element) => console.log(Element));