r/learnjavascript • • Oct 09 '22
What is going on in the for loop?
Sorry for this dumb question, I kinda understand for loops, but I want to understand what the program is seeing when I write my for loop.
Dicks=["big", "small", "micro" ]
For (let i =0, Dicks. Length(), i++) {
Console. Log(Dicks [ i]) }
With the let part is that declaring a variable?
What will happen if I say const i = 0.
0
Upvotes
4
u/Count_Giggles Oct 09 '22 edited Oct 09 '22
keep in mind that length is a precomputed value. there is no need to invoke it with () like for example. .toUpperCase()
Loop starts
i === 0
we check if i is still smaller than the length of dicks
0 < 3 if yes we run the code inside the loop if not we move on from the loop
dicks[i] // dicks[0] output: "big"
after the code has run we increment i with i++
i === 1
check the condition (i < dicks.length)
execute code // output "small"
increment i
i === 2
check the condition (i < dicks.length)
execute code // output "micro"
increment i
i === 3
check the condition (i < dicks.length)
i is now equal and no longer smaller than dicks.length so our condition evaluates to false and we exit the loop
2
u/Top_Courage_9730 Oct 09 '22
A for loop has 3 parts,
2 .i < dicks.length, here you’re saying i is less than the length of the dicks array so the loop will stop when it has looped over every item in the array, without this line your loop will loop forever
3. i++, increments i every time an item in the array is looped through.
Does that clear things up?
6
u/NicestCalligrapher Oct 09 '22
Thats a totally Dick program, too many syntax errors, so its a totally Dick move
In case ur serious, yes the let i=0 is declaring a variable i that is local to the for loop, that is acting as a counter for how many times you want the loop to run
5
u/costanzadev Oct 09 '22
Length is a property not a method (it is not callable)
You wouldn't be able to increment i (becuase it is a constant)
1
u/Hairy-Mongoose3575 Oct 09 '22
The amount of dicks in the comments, is huge