Var scopes(local/global)

Hello there!I have 2 programs/code below.Can you tell me why am i getting the same var ‘i’ values for both the programs. In the first(1.) program i have var ‘i’ inside the for condition so i am thinking that it should return an error when we use it outside of the for block.But over here it returns 3. Thanks in advance!
1.

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

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.

Challenge: Compare Scopes of the var and let Keywords

Link to the challenge:

Hello Inampudi.
The problem with the var keyword, among others, is that its life is not limited to its block, but either to the function scope or the global scope. Think of a block like a little house. The parenthesis where your var i lives, for example, is a house. Well, a var can be accessed outside of it. It’s as if you could see the i variable through the walls.

var i = 100 //global scope
if(true){//block
var x = 200
}
console.log(x) //=> 200. I can access it even if it's hidden inside 
the block after the if statement

//While with a function: 
function test(){

  var i = 100

}

console.log(i) //Error. i is hiding in a function, invisible from the outside

In your code the good variable finishes its work, then stops, but keeps being available from the outside. Another unpleasant think that may occur with the old var keyword is overwriting. From the example above

var random = 100; //global variable
function test(){

  var random = 300

}
console.log(random) //=> 300! You var was overwritten by mistake. 

All this little problems were solved with the implementation of the let and const keywords, introduced in 2015, covered in the ES6 notation section of the FCC curriculum. I hope I made it a bit clearer.
P.S.(Note also, on you second example, that your array stops at 2 because you’ve set loop to stop when i reaches 3; it does, stops the loop and keeps living in its comfortable block. If you wanted the array to get till 3 use the <= (smaller or equal) operator)
For even more information: the old var

1 Like

var is function scoped. the random outside still prints 100 as the one inside exists only inside the function

1 Like