JavaScriptMedium
What is local scope?
Local scope is the scope inside a function (or block): variables declared there are created when the function runs, are invisible from outside, and normally disappear when the call ends.
Key behaviours
- Each call gets a fresh scope. Calling a function twice creates two independent sets of local variables, which is what makes recursion work.
- Parameters are local variables. Reassigning a parameter does not affect the caller's variable. (Mutating an object passed in does, because both refer to the same object.)
- Inner code can see outer variables, not the reverse. A function can read variables from enclosing scopes through the scope chain.
- Locals can outlive the call if a closure still references them; otherwise they become eligible for garbage collection.
Why local scope is good
- Functions are self-contained and easier to test.
- No collisions with variables elsewhere.
- Memory is freed when the function finishes.
Common mistakes
- Forgetting
let/const(in sloppy mode this creates a global instead of a local). - Expecting reassignment of a parameter to change the original argument.
- Expecting a local declared in one function to be visible in another function called from it. Scope follows where code is written, not the call chain.
Code example
js
1function calculateTotal(items, taxRate) {2 const subtotal = items.reduce((sum, item) => sum + item.price, 0); // local3 const tax = subtotal * taxRate; // local4 return subtotal + tax;5}6console.log(calculateTotal([{ price: 10 }, { price: 20 }], 0.1)); // 337console.log(typeof subtotal); // "undefined" - not visible outside89// Each call has its own locals10function makeId(prefix) {11 let n = 0;12 return () => `${prefix}-${++n}`;13}14const userId = makeId("user");15const orderId = makeId("order");16console.log(userId(), userId(), orderId()); // user-1 user-2 order-11718// Reassigning a parameter vs mutating it19function update(value, obj) {20 value = 99; // only changes the local copy21 obj.changed = true; // changes the shared object22}23let num = 1;24const data = {};25update(num, data);26console.log(num, data); // 1 { changed: true }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.