I was looking for information about Scope and Closures, and I thought I had already understood it, when I see this example on the page that was the information:
let a = 1;
const function1 = function() {
console.log(a);
a = 2;
};
a = 3;
const function2 = function() {
console.log(a);
};
function1();
function2();
And it turns out that I do not understand the code because the result is 3
and 2
respectively, they can execute the code to check it.
As I understood, the variables declared with let
and const
were not applied to Hoisting , nor to the Expressions of functions , so seeing this code, no statement is applied to Hoisting , nor variables or function expressions .
According to how you explained that you had understood, when you get to the function expression with name function1
, the variable arrives with value 1
and prints that value, then changes the value with a = 2
and does not apply Hoisting because it is not a statement. When leaving this function, the new value a = 3
is assigned to it, and it does not apply Hoisting because it is not a declaration, and with this value it reaches the expression function with name function2
and would print 3
.
I do not know why it does not print 1
and 3
respectively. Here is the link in case you want to see it: