javascript loop over elements in 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: javascript loop through array

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

Example 3: how to loop through an array

int[] numbers = {1,2,3,4,5};
for (int i = 0; i < numbers.length; i++) {
	System.out.println(i);
}

Example 4: iterate through array js

let arbitraryArr = [1, 2, 3];
// below I choose let, but var and const can also be used 
for (let arbitraryElementName of arbitraryArr) {
  console.log(arbitraryElementName);
}