Beware, this is not true. Not all variables of a function are created independent of JS scope. See:
function x() {
y = 1;
var z = 2;
}
x();
console.log(y); // logs "1"
console.log(z); // Throws a ReferenceError: z is not defined outside x
When you declare a variable without the var
, the compiler declares the global variable, and if it has declared with var
, it creates within the scope.
However, in your code, you declared the variable with var
and he created the variable in global-Scope, why? His code works because in javascript the var
exists only in two types of scopes: global-scope
and function-scope
, which are the scopes created by functions. The block-scopes
, which are created by { ... }
, were created from ES6 with the creation of let
and const
. So, as you are using var, it is as if all your code is in the same scope, and so there is no error. Now, try:
function teste() {
var mensagem = "Olá!"; // declaração + atribuição
}
console.log(mensagem); // ReferenceError: mensagem is not defined
So, actually, before ES6, when it only existed var
, only variables could be created in global scope
and in the function scope
. Javascript had not block scopes
.
And at ES6 the Hoisting was not eliminated, but rather created the block scopes
, where the variables are created let
and const
. That’s why you wear let
or const
in your example gives error:
if(false) {
let mensagem = "Olá!"; // declaração + atribuição
}
console.log(mensagem); // ReferenceError: mensagem is not defined
The hoisting
exists because the interpreter javascript
execute your code in two steps: in the first, Compiler-Phase, all variables and functions are allocated in memory (it is as if we are passing the variables and functions up), and in the second, Execution-Phase, your code starts running line by line.
What we devs can take away from this is to be able to use variables and functions before they are declared:
i = 10;
var i;
and with methods:
issoEhHoisting();
function issoEhHoisting(){
console.log("aqui esta minha declaração");
}
The above D blocks only work because of the hoisting
.
But the question is: what is the point of having the Hoisting? Can you talk about it in the answer? You only talked about scopes.
– Woss
really, edited!
– guijob