Hi,
The var keyword here is defied globally so when you iterate through the for loop, it changes the actual value of the i.
This is not a good technique. Generally it is a better practice to not mutate the variables within the code.
So, with that in mind programmers often use let instead of var. Unless they want to change the variable somewhere in the code. One of the advantages of the let keyword is this:
When you declare a variable with the let keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
i++ adds one to the value of i after every iteration, then we evaluate the condition i<3 and only if it is true, we run the code in the loop, otherwise we move to the next line. So we did add 1 to the value of “i” which became 3 in the last iteration, but we dont push it to the array, because its value is not less then 3 anymore.
The same code can be written as follow:
var numArray = [];
var i=0; //initiate value as 0
while (i < 3) { //check condition before executing the loop
numArray.push(i);
i++ //change the iterator, to indicate an iteration was complete
}
console.log(numArray);
console.log(i);
if the condition is less than 3 how as you said So we did add 1 to the value of “i” which became 3 in the last iteration,
the for loop is not going to execute the code unless the ocndition is true
I’m also confused about this. It seems like the only way this works is if when the condition i=3 doesn’t meet the condition in the for loop (i < 3), we still store i = 3 for the next time we call that variable instead of i = 2. Is that correct? Why do we do that?