Closures and Lexical Scoping
Topic 8JavaScript Part 1
Closures and Lexical Scoping
Introduction
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 and Definitions
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(); // 2Lexical Scoping:
const globalVar = 'Global';
function outer() {
const outerVar = 'Outer';
function inner() {
console.log(globalVar, outerVar); // Access both variables
}
inner();
}
outer();Practice Exercises
- •Create a closure to manage a private variable.
- •Write a nested function and observe lexical scope behavior.
Interview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment