Skip to main content
TOPIC 8 OF 9 · 2 MIN READ

Closures and Lexical Scoping

A closure is formed when an inner function retains access to variables in its outer scope, even after the outer function has returned. Lexical Scoping determines how variable names are resolved based on the location of their declaration.

Key concepts

Closure

A combination of a function and its lexical scope. Allows data encapsulation.

Lexical Scoping

Variable access is determined by the position in the source code.

Examples

Closure:

function outer() {
  let counter = 0;
  return function inner() {
    counter++;
    console.log(counter);
  };
}
const increment = outer();
increment(); // 1
increment(); // 2

Lexical Scoping:

const globalVar = 'Global';
function outer() {
  const outerVar = 'Outer';
  function inner() {
    console.log(globalVar, outerVar); // Access both variables
  }
  inner();
}
outer();

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Create a closure to manage a private variable.
  • Write a nested function and observe lexical scope behavior.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus