loop through a javascript array 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: for in loop javascript
let array = [1,2,3,4,5,6,7,8,9,10];
// our array that we will use the for loop on
for (let i = 0; i < array.length; i++) {
// this loop will console log the element at array[i] starting at 0
// and will continue looping for i < array.length
console.log(array[i]);
// after each loop i will increase by 1
}
// this will console log
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
Example 3: javascript for loop[
for(i=0;i<=5;i++){
console.log(i);}