r/javascript • • Dec 16 '18

Coming from Python to JS NSFW

const print = console.log

I found my safe space.

607 Upvotes

156 comments sorted by

View all comments

Show parent comments

2

u/MrStLouis Dec 18 '18

I'm not entirely sure, and I think at some point the specs changed on it. The only for loops I think you can use const in are the for of and maybe for in. It's due to the nature of how that variable is scoped. Technically in a basic i<=length for loop you use the same i-variable over the course of the loop. With the other loops, each loop has its own version of the iterator. Using const is a good way to denote this technical difference in the loop, but in practice it's only really a safeguard to not change the iterator in your code. It doesn't affect anything other loop in the series to change it though. An interesting example would be to run each loop logging the iterator from a settimeout function. For 5 iterations the i-loop would log 4 5 times whereas the for of would log 0,1,2,3,4; because it is technically logging each loops unique iterator (sorry on mobile)

1

u/restart_kun Dec 19 '18

Thanks for the reply!