Advertisement
728x90
Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:
1. for..in iterates over all enumerable property keys of an object
2. for..of iterates over the values of an iterable object.
Let's explain this difference with an example,
javascript
1let arr = ["a", "b", "c"];
2
3arr.newProp = "newVlue";
4
5// key are the property keys
6
7for (let key in arr) {
8
9console.log(key); // 0, 1, 2 & newProp
10}
11
12// value are the property values
13
14for (let value of arr) {
15
16console.log(value); // a, b, c
17}Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of loop iterates over the values of a arr data structure and logs a, b, c in the console.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 78
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
421of476