This file covers three of the most common JavaScript interview themes: closures, this binding, and modular structure.
A closure happens when a function remembers variables from its lexical scope even after the outer function has finished executing.
- Closures are created naturally in JavaScript.
- They are used in callbacks, factories, modules, and event handlers.
- The function keeps access to variables, not frozen copies of values.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2- Thinking closure copies values once and never updates.
- Forgetting loop variables can produce closure bugs with
var.
A closure is a function bundled with access to the variables in the scope where it was created. That is why callbacks and factory functions can keep using outer variables after the outer function returns.
this is determined by how a function is called, not where it is written.
- Default binding
- Implicit binding
- Explicit binding with
call,apply, orbind newbinding
const user = {
name: "Ada",
showName() {
console.log(this.name);
},
};
user.showName(); // AdaArrow functions do not have their own this. They capture this from the surrounding lexical scope.
- Thinking
thispoints to the function itself. - Losing method context when passing a method as a callback.
- Using arrow functions where dynamic
thisis actually needed.
this is based on call-site rules. In regular functions it depends on how the function is invoked. In arrow functions it is lexically inherited from the surrounding scope.
Modules organize code, control visibility, and avoid global namespace pollution.
- CommonJS uses
requireandmodule.exports. - ES Modules use
importandexport. - Modules create boundaries that help maintainability and testing.
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./math.js";Before standard modules, closures were often used to simulate privacy.
function createStore() {
let value = 0;
return {
get() {
return value;
},
increment() {
value += 1;
},
};
}A function retaining access to variables from the scope where it was created.
By call-site rules for regular functions and lexically for arrow functions.
To organize code, reduce globals, improve reuse, and make dependencies explicit.