javascript loop through array
snippet in javascript

javascript loop through array

user5001

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 forEach
data.forEach((i) => {
  console.log(i) // 1 2 3 4 5 6
})
//BUT ->  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
})

javascript loop through array

user6020

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

javascript loop through array

user4214

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

javascript loop through array

user1905

const myArray = ['foo', 'bar'];

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

//or

for(let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

javascript loop through array

user8069

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

javascript loop through array

user9080

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

for (let item of array) {
  console.log(item);
}

javascript loop through array

user4191

let my_array = [1, 2, 3, 4, 5];

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

// for and of method
for(let i of my_array) {
	console.log(i)
}

/*
Results:
1 2 3 4 5
1 2 3 4 5
(From both methods)
*/

javascript loop through array

user1465

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

javascript loop through array

user8048

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

javascript loop through array

user6198

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