how to loop through list javascript 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

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)
*/

Example 3: how to loop through array of numbers in javascript

let numbers = [1,2,3,4,5];
let numbersLength = numbers.length;
for ( let i = 0; i < numbersLength; i++) {
    console.log (numbers[i]);
}