Sobes.tech
Middle+

Tell me, what is context in JavaScript, what is lexical environment, and how do closures work?

sobes.tech AI

Answer from AI

In JavaScript, the context (or 'this') is the value that is in the variable this inside a function. The context determines which object the function call belongs to. It depends on how the function is called: object method, call/apply, arrow functions, etc.

Lexical environment is a structure that stores variables and functions accessible in the current scope. It is formed during code compilation and determines which identifiers are available at a specific point in the program.

Closure is a function that 'remembers' its lexical environment even when called outside its original scope. This allows the function to access variables from an outer function after it has finished executing.

Example of a closure:

function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

Here, the inner function retains access to the variable count from the outer function, creating a closure.

Tell me, what is context in JavaScript, what is… - sobes.tech