pronoob
pronoob11mo 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
sean11mo 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
pronoob11mo ago
I see, so the increment happens at the end or the next iteration
sean
sean11mo ago
Yup it's the last step.
pronoob
pronoob11mo ago
Thank you so much! ❤️
sean
sean11mo ago
No problem, have a good one :)
pronoob
pronoob11mo ago
I was so confused
sean
sean11mo ago
Haha I get that
abi
abi11mo ago
It’s good to know how these loops work, but you should rarely (if ever) use them in your actual code 👍
NDH
NDH11mo ago
Why not? The good ol for loop is the fastest and most effective way to iterate!
TheYuriG
TheYuriG11mo ago
exactly, for loop is the fastest way to perform repeated tasks
NDH
NDH11mo ago
or iterate over objects or arrays!
NeTT
NeTT11mo ago
I found while loops to be slightly faster than for loops tho Tested back in 2020 NodeJS so I ain't sure
NDH
NDH11mo ago
Yes that's still true, The while only tests a Boolean, and the for-loop needs a test and an increment.
TheYuriG
TheYuriG11mo ago
that would make sense since those don't perform increments and neither instantiates a variable
NDH
NDH11mo ago
But if in the while-loop you need an index to do iteration, then it will be the same as for-loop.
abi
abi11mo ago
Heheh I just meant the indexed for-loop, the for-of is fine of course
NeTT
NeTT11mo 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
abi11mo ago
really? didn't know that. does the indexed for-loop perform better? <:pepe_think:946419068024528936>
NeTT
NeTT11mo 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
abi11mo ago
i hear you! but honestly, personally, unless it's absolutely crucial, i'd still avoid the indexed for-loop