First of all, one needs to understand the fact that whenever a function is called, the block it defines runs. A function (by itself) cannot maintain state between two or more different calls.
Note that within the function fora
, the function is defined dentro
. Thus, at all times that the function fora
is called, a new function dentro
, that will be returned to the caller.
This behavior can be verified by comparing the return of two calls to the same function, fora
. Behold:
function fora() {
const x = 'Local';
function dentro() {
return x;
}
return dentro;
};
const fn1 = fora(); // Criou uma função `dentro` (e retornou)
const fn2 = fora(); // Criou outra função `dentro` (e retornou)
console.log(fn1 === fn2); //=> false
How functions are, in their essence, objects (which implement the abstract operation [[Call]]
), the operator ===
analyzes if two functions have same reference. How we receive false
above, it is confirmed that every time a function is called, the functions defined therein are recreated.
Just out of curiosity, that’s why useCallback
exists in React. In some cases, recreating the same function in a colossal amount can be relatively costly. Thus, the memoisation to prevent the function from being recreated in each rendering.
But then even if the functions are recreated they will still have access to variable
x
which has been declared in the parent function bodyfora
, the functiondentro
is considered a closure that is something I did not quite understand how this works.– wdaniel
Theoretically the variable
x
is also recreated every timefora
is called, but as strings are immutable (and is there hard-coded) in this case makes little difference. If it were a literal object instead of a string, for example, we could also confirm thatx
is recreated with each call fromfora
. In relation to the operation of closures, suggest reading How Closures work in Javascript?.– Luiz Felipe