xxxxxxxxxx
// for loop shorthand javascript
// Longhand:
const animals = ['Lion', 'Tiger', 'Giraffe'];
for (let i = 0; i < animals.length; i++){
console.log(animals[i]);
// output:
// Lion
// Tiger
// Giraffe
}
// Shorthand:
for (let animal of animals){
console.log(animal);
// Lion
// Tiger
// Giraffe
}
// If you just wanted to access the index, do:
for (let index in animals){
console.log(index);
// 0
// 1
// 2
}
// This also works if you want to access keys in a literal object:
const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
console.log(key)
// continent
// country
// city
// Shorthand for Array.forEach:
function logArrayElements(element, index, array) {
console.log(index + " = " + element);
}
["first", "second", "third"].forEach(logArrayElements);
// 0 = first
// 1 = second
// 2 = third