This post is kind of a simplified version of this post:
What is the exact order of execution of Javascript's for loop?
I'm super interested in why I keep getting confused while working with for loops. I'd like to learn how a for loop is executed under the hood.
for (let i = 0; i < 10; i++) {
alert(i);
};
So from my understanding, this is as far as I get in understanding the order in which something like this is executed:
1) The engine initializes i = 0
2) The engine checks that i < 10
3) The engine pops out of the parenthesis that hold the for statement
4) The engine executes the code within the loop for this iteration
5) The engine pops back into the parenthesis to increment i
,
6) Repeat from step 2.
I guess I'm most confused about step #3. Does the engine actually pop out of the 'for' loop to execute the code within the block?
From my understanding, JavaScript is single-threaded and can only run synchronously, and so I'm a little confused at how in the middle of a 'for' statement, the engine can keep the status of the 'for' in memory while executing the code in the block.... unless each of the three conditions in the 'for' loop are their own independent commands, which can be executed and finished before moving on to the commands within the block.
I'm not even sure if I'm asking this question correctly, I'm still relatively new to programming, I only know vanilla JS at this point... next month is when I get into node ;)
Figured it Out: Click for an image of my breakpoint placement
I've learned that the order goes like this:
1) var i
is initialized to 0
2) var i
is checked for truthy
3) If true, code is executed,
4) Once execution is finished, i
is incremented
5) One incremented, i
is checked for truthy
6) Repeat steps 3 - 5 until i
is falsy
7) Iteration finished.
Thanks everybody. The Chrome debugger is a lot more powerful than I thought!