Compare Scopes of the var and let Keywords(don't understand from beginning)

Tell us what’s happening:
var numArray = [];
for (var i = 0; i < 3; i++) {
// returns [0, 1, 2]
// returns 3

//Why numArray returns [0,1,2] but console.log(i) returns 3 ?? Should this array be [1,2,3]

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:

Hey, why you are confused?

The challenge clearly explains the concept and difference between var and let

When you declare a variable with the var keyword, it is declared globally, or locally if declared inside a function.

The let keyword behaves similarly, but with some extra features. 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.

Let me clearly explain this to you.
In this challenge, you have to fix the scope of the global variable.

var i = 0; //global scope

if(true) {
   i = 5; // this will update the value of i to 5.

So to fix this, you have to declare the i variable local to if block ie where you have to use let or const

let i = 'global variable'; // global scope

if(true) {
   let i =  'Local-variable' ; // local /block scope.


Paste the code in browser console to see the result. I hope this clears your confusion.

Read more here…

Hi @hlhnicola !

So I’ve been racking my brain over this one for a few minutes. I sat here thinking exactly the same thing and couldn’t for the life of me understand why 3 was being returned instead of 2… and then EUREKA! And boy do I feel stupid now…

Actually, I say that, but quite frankly the formatting of the example code could be improved here.

So here we go:

  1. We have a for loop. As i’m sure you’ve picked up by now for loops work in this pattern…

set variable (var i = 0; in this case) --> execute following code (numArray.push(i)) where condition is true (i<3) --> do something at the end of each iteration (increment i with i++).

  1. We can follow through each iteration of the loop to see what happens!

Iteration 1:

i starts as 0
i is less than 3 so i (0 at the moment) is pushed to the array
i is incremented by 1 to become 1

Iteration 2:

i starts as 1
i is less than 3 so i (1 at the moment) is pushed to the array
i is incremented by 1 to become 2

Iteration 3:

i starts as 2
i is less than 3 so i (2 at the moment) is pushed to the array
i is incremented by 1 to become 3

Iteration 4:

i starts as 3
i is NOT LESS THAN 3 so loop ceases execution

  1. So at this point our loop has ended. Notice how when i is incremented in the third iteration that it takes the value 3, this is what causes the loop to exit (before executing code) on the next iteration.

This is why now, when we get the console to log i, it returns 3.

I find it really helps to work through iterations of loops in situations like this!

1 Like