Lexical scope, closures, and the scope chain explained with a short code example each.
35 cards · basic cards · AI-written, checked twice. Edit anything.
- What is lexical scope in JavaScript?
Show answer
Scope determined by where variables and functions are declared in the code. Inner functions can access variables from their enclosing scopes.
- Show a simple lexical scope example.
Show answer
function outer() { let x = 5; function inner() { console.log(x); } inner(); } inner can access x because it is in outer's lexical scope.
- What is a closure?
Show answer
A function that remembers and accesses variables from its enclosing scope even after that scope has finished executing.
- Show a closure example with a counter.
Show answer
function makeCounter() { let count = 0; return function() { count++; return count; }; } const c = makeCounter(); c() returns 1, then 2. The returned function closes over count.
- What is the scope chain in JavaScript?
Show answer
The mechanism that looks up a variable by searching the current scope, then parent scopes, until reaching global scope.
- What happens when you reference a variable not in local scope?
Show answer
JavaScript searches parent scopes up the scope chain. If not found anywhere, a ReferenceError is thrown.
- What is function scope?
Show answer
Variables declared inside a function are only accessible within that function and nested functions inside it. var has function scope.
- What is block scope?
Show answer
Scope limited to code blocks (curly braces). let and const have block scope. Variables declared in a block are not accessible outside it.
- How does var differ from let and const in scope?
Show answer
var has function scope, let and const have block scope. var is also hoisted and can be redeclared in the same function scope.
- What is global scope in JavaScript?
Show answer
The outermost scope accessible from anywhere in the program. Variables declared at the top level without a function or block are global.
- What are free variables?
Show answer
Variables referenced in a function but declared in an outer scope. Free variables are what make closures possible.
- Show an example of free variables.
Show answer
function outer() { let x = 10; function inner() { return x + 5; } } In inner, x is a free variable because it is declared in outer, not inner.
- What is variable shadowing?
Show answer
Declaring a variable in an inner scope with the same name as a variable in an outer scope, which hides the outer variable.
- Show a variable shadowing example.
Show answer
let x = 1; function f() { let x = 2; console.log(x); } f() logs 2, not 1. The inner x shadows the outer x.
- What is hoisting in JavaScript?
Show answer
Variable and function declarations are moved to the top of their scope during compilation. Initializations remain in place.