Ways of looping through Arrays in ES5:
let array = [1,2,3];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
array.forEach(function (value) {
console.log(value);
});
Downsides:
You can’t break out of this loop using a break statement or move to the next iteration with continue.
You can’t return from the enclosing function using a return statement.
The for-in loop is designed for iterating over an objects properties, like so:
var obj = {a:1,b:2};
for (let prop in obj) {
console.log(prop); //prints a, b
}
If we tried to use it with an array:
let array = [10,20,30];
for (let index in array) {
console.log(index); // prints '0', '1' ... converts the index to a string
});
To iterate over key / values of an object:
for (var key in optionsDocumentTypes) {
if (optionsDocumentTypes.hasOwnProperty(key)) {
console.log(key + " : " + optionsDocumentTypes[key]);
}
}
In ES6 we have a new syntax:
The for–of loop is for looping over the values in an array. It also works on most array-like objects including the new Set and Map types.
let array = [10,20,30];
for (var value of array) {
console.log(value); // prints 10, 20, 30
}