169. Advanced Loop

변지영·2022년 2월 25일
0

for

const basket = ['apples', 'oranges', 'grapes'];

for ( let i = 0; i<basket.length; i++){
	console.log(basket[i]);
}

forEach

const basket = ['apples', 'oranges', 'grapes'];


basket.forEach(item =>{
	console.log(item);
})

for of

  • 'for of' loop only works with iterable
for (item of basket){
	console.log(item);
}

iterables (반복가능한)

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

'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)
}

enumerable (나열 가능한)

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.

  • 'for of' loop only works with 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.

0개의 댓글