🟢 EasyCore JS📖 Theory Question

What is lexical scope and how does it affect closures?

💡

Hint

Scope is determined where code is written, not where it is called

Full Answer

Lexical scope (static scope) means a function's scope is determined by where it is written in the code — at author time — not by where it is called at runtime.

const x = 'global';

function outer() {
  const x = 'outer-fn';
  function inner() {
    console.log(x); // 'outer-fn' — closes over WHERE inner is DEFINED
  }
  return inner;
}

const fn = outer();
fn(); // logs 'outer-fn', NOT 'global'
// Even though fn() is called at global level, it remembers outer-fn's scope

This is what makes closures possible — a function carries its scope from where it was created, not from where it's invoked.

💡 Contrast with dynamic scope (Bash, Perl): if JS were dynamic, fn() would print 'global' because it's called there. Lexical scope is more predictable and is the reason closures work.

More Core JS Questions

🟢 EasyWhat is the difference between var, let, and const?→🟢 EasyExplain closures with a practical example.→🟢 EasyWhat is hoisting in JavaScript?→🟢 EasyExplain the event loop, call stack, and microtask queue.→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint