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