Javascript: Example with Scope and Closures

0

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:

link

    
asked by Daniel Sandoval 15.07.2018 в 07:04
source

1 answer

0

It is because at no time does it enter with 1. Until you call the functions all are assignments and information load.

First you are saying that a is 1. Then you say that there is a function that shows on screen and that is going to be worth 2, but you are not saying that the function is executed, you are just saying how it should behave.

Then you say that a is worth 3, therefore the value 1 has already been lost. The following is another statement of a function that prints to.

The problem is that so far you have only told JavaScript "Hey, I have a variable that is going to be worth 1, a function that when you call it will print and then its value will change to 2, now I think it is better to change the value of a to 3, and now prepare another function to print the value you have to A. Lastly, execute everything ".

If you follow the steps you will see that when you call the function a is already worth 3, because the functions have not yet been invoked, therefore a enters the first function with the value 3, it is printed and it changes to 2 and it is the function ends Then there is another call, to the second function, and when it enters value 2, which is the last modification that has been made to the variable.

With all this talk I come to say, the declaration of a function does not make it run. It only does so when it is explicitly invoked.

    
answered by 15.07.2018 / 09:18
source