Each function creates its scope. The var
when declared/used within a function declares that variable and blocks access to variables with the same name outside that scope. However, in the lines preceding the line where var
is used, the variable value is not yet defined...
Javascript can use declared functions before running the code but variables are only used when the code reaches the line where they are. This is called Hoisting and the difference is:
function add() {} // function declaration - disponível em todo o escopo
var add = function () {} // function expression - declarada em todo o escopo,
// mas só disponível depois da linha ter sido corrida
Look at the example:
function a() {
b();
console.log(1, foo, typeof foo); // 1 undefined undefined
var foo = 'bar';
console.log(2, foo, typeof foo); // 2 bar string
try {
console.log(3, inexistente, typeof inexistente); // dá erro
} catch (err) {
console.log(4, err.message); // 4 inexistente is not defined
}
function b() {
console.log(5, foo); // 5 undefined - a função corre mas a variável não
}
}
a();
In the case of the variable with the name inexistente
the code knows that even if it has not been declared on the lines being executed, that variable is never declared. Hence the error.
Note: execution context refers to the this
, your question refers to Hoisting and scope of variables.