Compare Scopes of the var and let Keywords want to understand what is hapening

Hi I am just trying to understand this lesson but I cannot grasp this specific part

var numArray = [];
var i;
for (i = 0; i < 3; i++) {
  numArray.push(i);
}
console.log(numArray);
console.log(i);

why the var i printed 3 in the console while the condition in the for loop is less than 3 as long as i inserted inside the for

lesson link

lesson link Compare Scopes of the var and let Keywords

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.

In simple terms:

var is function scoped and let is block scoped

1 Like

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);

For loop is simply a conveniant shorthand

1 Like

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?