0

In the code below, I have declared variable i on for loop , and trying to access variable i and I can get the last updated value of i, how.

for(var i = 0; i <= 10; i++){
   console.log(i);
}

console.log(i,'outside');
Mr.Nimelo
  • 316
  • 4
  • 17
Vishal Pachpande
  • 500
  • 5
  • 19

2 Answers2

8

The var statement declares a variable in the scope of the current function, not the current block (which is what the let statement is for).

After the for loop, you are still in the same function, so the variable still exists (with whatever value it was last set to).

(NB: For the purposes of var, the code which runs outside of any function is effectively treated as being in a function of its own).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Well, you are using var, and that's exactly a var type should do!

We have var and let, let's see how they work.

when you declare your variable like this :

let something; 

You only access something in that very scope (for example your own for loop), and outside the scope, you cannot have it. On the other hand, when you are using var type, like this :

var something;

You are able to use this variable outside the scope ( again like your own for loop )

Notice that we are not talking about global variables. we are just talking about scopes.

If you rather declare a global variable, just use var in the global scope.

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150