A function created within another function is created with each call or persisted by reference?

Asked

Viewed 74 times

9

In the call for the declaration const minhaFuncao = fora(), i am storing the function execution result fora, that in this case would be the function dentro in minhaFuncao. In this case, am I creating a new function? Or am I just pointing to where the function was set?

const x = 'Global';

function fora() {
    const x = 'Local';
    function dentro() {
        return x;
    }
    return dentro;
};

const minhaFuncao = fora(); 
console.log(minhaFuncao());

1 answer

9

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 body fora, the function dentro is considered a closure that is something I did not quite understand how this works.

  • Theoretically the variable x is also recreated every time fora 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 that x is recreated with each call from fora. In relation to the operation of closures, suggest reading How Closures work in Javascript?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.