DEV Community

Discussion on: 17 Javascript optimization tips to know in 2021 🚀

Collapse
estruyf profile image
Elio Struyf

Great list, just one thing in tip number 6 foreach Loop Shorthand. A for...in is not the same as a for...of loop!

With the for...in you iterate over the object its properties. For the for...in with an array, you'll get the index value.

With the for...of you iterate over all elements inside the array, so i will be the element and not the index.

Collapse
bugmagnet profile image
Bruce Axtens

Thanks for pointing that out, @estruyf . The following deno session demonstrates

> const b = "abcdef".split("")
undefined
> b
[ "a", "b", "c", "d", "e", "f" ]
> for (let x in b) console.log(x)
0
1
2
3
4
5
undefined
> for (let x of b) console.log(x)
a
b
c
d
e
f
undefined
Enter fullscreen mode Exit fullscreen mode