looping an array code example

Example 1: loop through an array javascript

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

// Here's 4 different ways
for (let index = 0; index < array.length; index++) {
  console.log(array[index]);
}

for (let index in array) {
  console.log(array[index]);
}

for (let value of array) {
  console.log(value); // Will log value in array
}

array.forEach((value, index) => {
  console.log(index); // Will log each index
  console.log(value); // Will log each value
});

Example 2: js loop array

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

Example 3: how to cycle through an array js

// Requiring the lodash library 
// src: https://lodash.com/docs/4.17.15#forEach

// console:  npm i --save lodash
const _ = require("lodash")

// Use of _.forEach() method

_.forEach([1, 2], function(value) {
  console.log(value)
});
// => Logs `1` then `2`.

// traversing an object
_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
  console.log(key)
})
// => Logs 'a' then 'b' (iteration order is not guaranteed).

//////////////// To not use lodash ////////////////
// src: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element)
}
[2, 5, 9].forEach(logArrayElements)
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

Tags:

Misc Example