Functions. Closures.

Simple example:

const addOne = function () {
  let num = 10;

  return function () {
    return console.log(num++);
  };
};

const exp = addOne();
exp(); // 10
exp(); // 11
exp(); // 12

const expAdd = addOne();
expAdd(); //?
expAdd(); //?
expAdd(); //?

Try to solve this example on your own:

let appelAdd;

const appels = function () {
  const totalAppels = 10;

  appelAdd = function () {
    console.log(totalAppels + 1);
  };
};

appels();
appelAdd(); //?
  1. First, the global lexical environment is created:
Step 1
  1. Then, appels() is called.
Step 2
  1. Inside appels, a new function is created and assigned to appelAdd:
appelAdd = function () {
  console.log(totalAppels + 1);
};
Step 3
  1. appels() → finished. But its lexical environment is still accessible:
Step 4
  1. Then, appelAdd() is called. JavaScript executes the function.
Step 5
Main rule: a function remembers where it was created. The [[Environment]] reference is set once and for all when the function is created.