const basket = ['apples', 'oranges', 'grapes'];
for ( let i = 0; i<basket.length; i++){
console.log(basket[i]);
}
const basket = ['apples', 'oranges', 'grapes'];
basket.forEach(item =>{
console.log(item);
})
for (item of basket){
console.log(item);
}
Iterable: Javascript provides you can iterate
over arrays and strings.
Instead of basket, put 'basket'
for (item of 'basket'){
console.log(item);
}
^ iterating over the string one by one.
'for in' loop allows us to loop over and see the object properties
const detailedBasket = {
apples: 5,
oranges: 10,
grapes: 1000
}
for (item in detailedBasket){
console.log(item)
}
for objects.
(available in for in loop)
If I switch basket to detailedBasket(object) with 'for of' loop, I got an error.
for (item of detailedBasket){
console.log(item);
}
Instead of basket, put detailedBasket. then I got an error detailedBasket is not iterable.
If I switch detailedBasket to basket(array) with 'for in' loop, there's no problem.
for (item in basket){
console.log(item)
}
Conclusion
- 'for in' loop for objects [enumerable]
- 'for of' loop for arrays & strings [iterable]
- 'for of' loop doesn't work with objects because they are not iterable.