javascript iterate 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 code to loop through array

var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

Example 3: iterate through list javascript

const array = ["hello", "world"];

for (item of array) {
	//DO THIS
}

Example 4: js loop through array

// ES6 for-of statement
for (const color of colors){
    console.log(color);
}

// Array.prototype.forEach
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

// Sequential for loop
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

Example 5: loop over an array

let fruits = ['Apple', 'Banana'];

fruits.forEach(function(item, index, array) {
  console.log(item, index);
});
// Apple 0
// Banana 1

Example 6: iterate through array javascript

for (var key in validation_messages) {
    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if (!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}