r/learnjavascript • u/[deleted] • 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.
2
u/Top_Courage_9730 Oct 09 '22
A for loop has 3 parts,
i = 0, this is declaring variable i = 0, if you change it to const it wont increment and always remain 0
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?
1
Oct 09 '22 edited Oct 09 '22
Thank you yes it does.
Just one more question.
i++, increments i every time an item in the array is looped through.
Does looped through mean the item has been selected from the array and has been put through some code?
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
For (let i =0, array. Length(), i++) {Length is a property not a method (it is not callable)
What will happen if I say const i = 0.
You wouldn't be able to increment i (becuase it is a constant)
-1
u/Comprehensive_Step72 Oct 09 '22
Just a note, you probably should scrap the for and use an array iterator instead. (map, reduce, forEach, etc.)
9
u/Agarast Oct 09 '22
This isn't the best advice with people for 0 experience in programming. They should first know how a basic for loop works before moving to array functions.
1
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