Full-time web dev; JS lover since 2002; CSS fanatic. #CSSIsAwesome
I try to stay up with new web platform features. Web feature you don't understand? Tell me! I'll write an article!
He/him
Yeah, the difference seems to be that in a for ... of loop like this:
for(constthingofmyThings){/*...*/}
you're essentially grabbing an iterator at the start of the loop, i.e. myThingsIter = myThings[Symbol.iterator](), then at the beginning of each loop running const thing = myThingsIter.next(). It seems to desugar to something like this:
You're always assigning a whole new value to the loop variable as opposed to modifying the loop variable as is typical in a classic for (let i=0; i<n; i++) loop.
Really the only reason you need a let in that loop is because you're reassigning the value with i++, equivalent to i = i+. In theory you can use a const if you're doing something super unusual, like using an object as your loop variable and modifying a property of it:
I don't know why anyone would ever want something like this, and there would undoubtedly be cleaner ways to write the code, but it works. You're never reassigning o, so no problem with it being a const.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Yeah, the difference seems to be that in a
for ... of
loop like this:you're essentially grabbing an iterator at the start of the loop, i.e.
myThingsIter = myThings[Symbol.iterator]()
, then at the beginning of each loop runningconst thing = myThingsIter.next()
. It seems to desugar to something like this:You're always assigning a whole new value to the loop variable as opposed to modifying the loop variable as is typical in a classic
for (let i=0; i<n; i++)
loop.Really the only reason you need a
let
in that loop is because you're reassigning the value withi++
, equivalent toi = i+
. In theory you can use aconst
if you're doing something super unusual, like using an object as your loop variable and modifying a property of it:I don't know why anyone would ever want something like this, and there would undoubtedly be cleaner ways to write the code, but it works. You're never reassigning
o
, so no problem with it being aconst
.