0

Consider the following for loop in Javascript.

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

If i run the code, I will get 10 in the console. Why is this? How is the scope of variable 'i' available outside for loop ?

Roshan FIS
  • 11
  • 3
  • 4
    Javascript does not have block scope, it has only function level scope.... – Arun P Johny Nov 25 '15 at 04:06
  • 4
    Although you have [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) in ES6 – Arun P Johny Nov 25 '15 at 04:06
  • JS Hoists all of the vars declared in a function to the starting of function, so all of them are available throughout the function. NOTE: although if they are used before their declaration in function, their value will be undefined – Sukrit Gupta Nov 25 '15 at 04:11
  • There is also global scope. – RobG Nov 25 '15 at 04:11

1 Answers1

0

In javascript, there is no block level scope prior to ES6 (with let), so any variable you declare will have a function level scope (if the declaration is inside a function) or global scope.

JavaScript before ECMAScript 6 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531