+ 1

JavaScript arrays loops.

Hi guys. I tried to loop on an array and I don't understand why the results are different. The array is : var names =["Joe", "Don", "Theo", "Drew"]. When I use : for(var i in names) {console.log(i)}, I get 1,2,3,4. But when I use for(var i of names) {console.log(i)}, I get Joe, Don, Theo, Drew. Can someone please explain to me why?

21st Jun 2020, 11:50 AM
ABODO ELOUNDOU
ABODO ELOUNDOU - avatar
2 Respostas
+ 2
"in" is used to iterate over an object. So in for (var i in names) names[i] can be used to get the values (i iterates over the keys). When "in" is used to iterate over an array, i takes the value of the index. With for (var i of names) i takes the value of each element. "in" is not recommended to be used to iterate over an array. More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
21st Jun 2020, 12:08 PM
Russ
Russ - avatar
+ 1
Thanks for the reply, very helpful
23rd Jun 2020, 6:35 AM
ABODO ELOUNDOU
ABODO ELOUNDOU - avatar