Javascript - No Block-Level Scopes with var

Introduction

Consider the following code

if (true) {
    var color = "blue";
}

console.log(color);    //"blue"

Here, the variable color is defined inside an if statement.

In JavaScript the variable declaration adds a variable into the current execution context.

For for loop control variable:

for (var i=0; i < 10; i++){
    doSomething(i);
}

console.log(i);    //10

In JavaScript, the i variable is created by the for statement and continues to exist outside the loop after the statement executes.

Related Topic