+ 5

JS for...in/of differences​

I don't understand​ why in case1 for...of works fine and in the case3 for...in. They are both (...args & ...rest) the same thing right (array, or object actually)? So, what makes them behave differently? For example in case2 it fails​ which is reasonable. https://code.sololearn.com/WVOfj0T84XZ8/?ref=app

22nd May 2017, 9:19 PM
Aaron Sarkissian
Aaron Sarkissian - avatar
4 Answers
22nd May 2017, 9:33 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
@Ulisses Thanks for the link, but I didn't get my answer. I changed my question little bit. The thing is that I know how they should behave, but they are behaving opposite in case1 & case3, while failing in case2.
22nd May 2017, 10:08 PM
Aaron Sarkissian
Aaron Sarkissian - avatar
+ 3
@Aaron what is happening in the first case is: because you are using the for/of, in any iteration of the loop you get a value of iterator args 2, 3, 4, 5. In this case typeof value is 'number', that's why the return value is 3.5. in case 2: because you are using for/in, you are iterating through the property of args (I think is the index property). The value2 variables get '0', '1', '2', '3' (typeof value2 is 'string'). In the end of the for loop sum2 = '0123' which divided by 4 is 30.75.
22nd May 2017, 10:31 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 3
in for...of loop, in every iteration you will get an array value. but for...in loop, in every iteration you will get an array item index not the value. so to fix your code you should use this inside for..in loop. sum2 += args2[value2];
22nd May 2017, 10:55 PM
Apel Mahmod
Apel Mahmod - avatar