Javascript Variable Scope

#javascript

Pre ECMAScript 6 examples

Global

The variable is available to the entire document.

var i = 10;

Examples

var i = 10;

if (true) {
    i = 20;
}

function runme() {
    i = 30;
}

console.log(i); // 20
runme();
console.log(i); // 30

Hoisting

Declarations can come after initializations.

i = 10;
j = 20;

function add() {
    return i + j;
}

var i, j;

console.log(add()); // 30

Local

The variable is available to the current function.

function runme() {
    var i = 20;
}

Examples

function runme() {
    var i = 20;
}

console.log(i); // Uncaught ReferenceError: i is not defined

[1] 1