pronoob
pronoob15mo ago

Question about for loops

Why does the following code log numbers from 0 to 9 instead of 1 to 9? i is assigned as zero in the first expression, then it checks whether i is less than 10 and moves to the next expression which is i++, so it should increment the value of i to 1 instead and log it
for (let i = 0; i < 10; i++) {
console.log(i);
}
for (let i = 0; i < 10; i++) {
console.log(i);
}
20 Replies
sean
sean15mo ago
Think about it step by step. You have a variable i with a value of 0 You check if i < 10. If it is, you log the current value. If it isn't, you exit the loop. You increment i.
pronoob
pronoob15mo ago
I see, so the increment happens at the end or the next iteration
sean
sean15mo ago
Yup it's the last step.
pronoob
pronoob15mo ago
Thank you so much! ❤️
sean
sean15mo ago
No problem, have a good one :)
pronoob
pronoob15mo ago
I was so confused
sean
sean15mo ago
Haha I get that
abi
abi14mo ago
It’s good to know how these loops work, but you should rarely (if ever) use them in your actual code 👍
NDH
NDH14mo ago
Why not? The good ol for loop is the fastest and most effective way to iterate!
TheYuriG
TheYuriG14mo ago
exactly, for loop is the fastest way to perform repeated tasks
NDH
NDH14mo ago
or iterate over objects or arrays!
NeTT
NeTT14mo ago
I found while loops to be slightly faster than for loops tho Tested back in 2020 NodeJS so I ain't sure
NDH
NDH14mo ago
Yes that's still true, The while only tests a Boolean, and the for-loop needs a test and an increment.
TheYuriG
TheYuriG14mo ago
that would make sense since those don't perform increments and neither instantiates a variable
NDH
NDH14mo ago
But if in the while-loop you need an index to do iteration, then it will be the same as for-loop.
abi
abi14mo ago
Heheh I just meant the indexed for-loop, the for-of is fine of course
NeTT
NeTT14mo ago
That was the case I tested When I went beyond 1M iterations While loop showed some difference for..of performs really bad for larger arrays tho.
abi
abi14mo ago
really? didn't know that. does the indexed for-loop perform better? <:pepe_think:946419068024528936>
NeTT
NeTT14mo ago
Way better for..of is fine in places it's required or when you don't have a lot of elements to iterate But it's hella slow as the size increases
abi
abi14mo ago
i hear you! but honestly, personally, unless it's absolutely crucial, i'd still avoid the indexed for-loop