JavaScript Interview Questions Every Dev Should Know — Part 2: Functions, Scope & Closures
Welcome to Part 2 of the JS interview series! This time we're tackling functions, scope, and the topic that trips up even experienced developers in interviews: closures . Missed Part 1? Check out Fundamentals & Data Types first. Q1. What is a closure? A closure is what happens when an inner function "remembers" and continues to have access to the variables from its enclosing (outer) function's scope, even after that outer function has already finished running and would normally have had its local variables cleaned up. This works because JavaScript functions don't just capture the values of outer variables — they capture live references to them, keeping the entire surrounding scope alive in memory for as long as the inner function itself is reachable. Closures are one of the most powerful and commonly used patterns in JavaScript. They're the mechanism behind data privacy (since variables inside a closure can't be accessed from outside except through the functions that were given access), factory functions that generate customized functions, memoization caches, and event handler callbacks that need to remember state from when they were created. In the classic counter example below, each call to counter() creates a fresh, independent count variable that only the returned function can see or modify — there's no way to reach into it from outside. function counter () { let count = 0 ; return () => ++ count ; } const inc = counter (); inc (); // 1 inc (); // 2 Q2. What is lexical scoping? Lexical scoping (also called static scoping) means that a variable's accessibility is determined entirely by where it's physically written in your source code — not by which function called which, or the order in which functions happen to execute at runtime. When JavaScript compiles your code, it can already determine, just by looking at the nesting of functions and blocks, exactly which variables any given piece of code will be able to see. This is what allows an inner function to "reach