Modules & Scope 📦
Modularity and scope keep code organized and prevent accidental leaks into global space.
1) Lexical Scope 🧠
- JavaScript determines scope by where functions are written, not called.
- Inner scopes can read variables from outer scopes; the reverse isn’t true.
function outer() {
const secret = "😎";
function inner() {
console.log(secret);
}
inner();
}2) Closures 🔒
- Functions carry references to outer variables even after outer function returns.
- Use for encapsulation, memoization, and event handlers.
3) IIFEs (Immediately Invoked Function Expressions) ⚡
(() => {
const privateVar = 42;
console.log(privateVar);
})();- Old-school way to create a private scope before modules were widely supported.
4) ES Modules 📚
- Use
exportandimportfor structured dependencies.
// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14;
// usage
import { add, PI } from "./math.js";- Default exports:
export default function greet() {}
import greet from "./greet.js";- Tree-shakable, async-friendly, supported in modern bundlers/browsers.
5) CommonJS (Legacy) 🧳
// Node.js classic
module.exports = { add };
const { add } = require("./math");- Still common in older Node projects; prefer ES modules when possible.
Key Takeaways ✅
- Lexical scope + closures create predictable access to variables.
- IIFEs provide private scopes when modules aren’t available.
- ES modules organize code with explicit imports/exports; default vs named exports serve different ergonomics.
Recap 🔄
Understanding scope, closures, and modules helps you structure JavaScript like a well-organized toolbox—no accidental globals, clear collaboration between files, and easy code splitting.
Last updated on