Sub topic 3
Function Scope
This chapter assumes you can declare variables with var, let, and const, write and call functions, and run code in a browser console or Node.js. You should also know that JavaScript uses lexical scope, meaning a name's visibility depends on where the code is written, and that the global scope sits at the outermost level.
Function scope is the oldest scoping unit in JavaScript. Before ES2015 added let and const, a function was the only way to make a variable private in a script. That is still why var behaves the way it does, and why older libraries are wrapped in functions.
What a Function Scope Contains
Every function body defines a scope. Names declared inside it are local, which means they are visible inside the function and invisible outside it. A function scope holds:
- The function's parameters.
- Every
vardeclaration anywhere in the body, including inside nested blocks. - Every function declaration directly in the body.
let,const, andclassdeclarations at the top level of the body. Declarations inside nested blocks belong to those blocks, which the next chapter covers.
function computeTotal(price, quantity) {
var subtotal = price * quantity;
const tax = subtotal * 0.2;
return subtotal + tax;
}
console.log(computeTotal(10, 3)); // 36
console.log(typeof subtotal); // "undefined"
console.log(typeof tax); // "undefined"
console.log(typeof price); // "undefined"None of price, quantity, subtotal, or tax exists outside computeTotal. Using typeof on them is safe here because the global scope never declared those names.
Visibility goes in one direction only. Code inside a function can read names from the scopes around it. Code outside cannot reach in.
Each Call Gets a Fresh Scope
A function scope is created when the function is called, not when it is defined. Every call builds a new set of local variables, and that set is thrown away when the call ends, unless something still refers to it.
function makeLabel(prefix) {
let counter = 0;
counter += 1;
return prefix + "-" + counter;
}
console.log(makeLabel("a")); // "a-1"
console.log(makeLabel("b")); // "b-1"
console.log(makeLabel("a")); // "a-1"counter starts at 0 on every call because each call has its own counter. A common beginner mistake is to expect a local variable to keep its value between calls. If you want state that lasts, it has to live in an outer scope or in a closure, which a later chapter covers.
Recursion depends on this behavior. Each recursive call has its own parameters and locals, so the calls do not overwrite one another.
var Belongs to the Function, Not the Block
A var declaration attaches to the nearest enclosing function, or to the script if no function encloses it. Braces from if, for, or while have no effect on it.
function findFirstEven(numbers) {
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
var found = numbers[i];
break;
}
}
return { found, i };
}
console.log(findFirstEven([3, 7, 8, 10])); // { found: 8, i: 2 }
console.log(findFirstEven([1, 3])); // { found: undefined, i: 2 }i and found are both visible at the return line, even though they were declared inside a loop and an if block. In the second call the if body never runs, yet found still exists with the value undefined. The declaration belongs to the whole function from the start. The assignment just never happened. The chapters on hoisting explain the timing in detail.
Parameters Are Local Variables
Parameters act like local variables that start out holding the arguments. Assigning a new value to a parameter changes only the local binding. Changing a property of an object you received does affect the caller, because both sides refer to the same object.
function reset(value, settings) {
value = 0;
settings.mode = "off";
}
let n = 5;
const config = { mode: "on" };
reset(n, config);
console.log(n); // 5
console.log(config.mode); // "off"This difference between reassignment and mutation is a frequent source of confusion. Scope controls which names are visible. It does not copy the objects those names refer to.
Redeclaring a parameter
A var with the same name as a parameter is allowed, and it does not reset the value. A let or const with that name is a SyntaxError, so the code never runs.
function keep(a) {
var a; // same binding as the parameter
return a;
}
console.log(keep(7)); // 7
// function broken(a) { let a; } // SyntaxError: Identifier 'a' has already been declaredNested Functions
A function defined inside another function gets its own scope, nested inside the outer one. The inner function can read the outer function's locals. The outer function cannot read the inner function's locals.
function outer() {
const secret = 42;
function inner() {
const innerOnly = secret + 1;
return innerOnly;
}
const result = inner();
console.log(typeof innerOnly); // "undefined"
return result;
}
console.log(outer()); // 43The inner function inner is itself a local name of outer. Code outside outer cannot call it. Putting helper functions inside the only function that uses them keeps the global scope clean.
Arrow Functions and Methods Have Function Scope Too
Arrow functions, methods, and async and generator functions all create a function scope for their parameters and declarations. Arrow functions differ in other ways: they have no this or arguments of their own. Variable scoping is the same as for any other function.
const double = (x) => {
const result = x * 2;
return result;
};
console.log(double(4)); // 8
console.log(typeof result); // "undefined"Named Function Expressions Scope Their Own Name
When you give a function expression a name, that name is visible only inside the function. This lets the function refer to itself, for recursion, without adding a name to the outer scope.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"The outer scope only gets factorial. Recursion through fact keeps working even if factorial is later reassigned to something else.
Using Function Scope for Privacy: the IIFE
An immediately invoked function expression (IIFE) is a function that is defined and called in a single expression. Before modules and block scope existed, it was the standard way to create a private scope.
const counter = (function () {
let count = 0;
return {
increment() {
count += 1;
return count;
},
reset() {
count = 0;
}
};
})();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(typeof count); // "undefined"count lives in the IIFE's function scope. Only the two methods can reach it. You will still see this pattern in older code and bundler output. In new code, ES modules and block scope usually do the job, and later chapters cover both.
Edge Case: Default Parameters Get Their Own Scope
When a function has a default parameter value, the parameters are evaluated in a scope of their own. That scope sits between the outer scope and the function body. Default expressions can see earlier parameters and outer variables. They cannot see declarations in the body.
const x = "outer";
function demo(a = x) {
const x = "body";
return a;
}
console.log(demo()); // "outer"The default x resolves to the outer x, because the body's x is in a separate, inner scope.
Parameters are also initialized from left to right. A default that refers to a later parameter hits that parameter before it is initialized and throws:
function order(a = b, b = 1) {
return a + b;
}
try {
order();
} catch (e) {
console.log(e.name); // "ReferenceError"
}
console.log(order(2)); // 3The second call works because a gets an argument, so its default never runs.
Summary Table
| Declaration inside a function | Scope it belongs to | Visible outside the function? |
|---|---|---|
| Parameter | Function (parameter scope if defaults exist) | No |
| `var` anywhere in the body | Whole function | No |
| Function declaration at top level of body | Whole function | No |
| `let` / `const` / `class` at top level of body | Function body | No |
| `let` / `const` inside a nested block | That block only | No |
| Name of a named function expression | The function itself | No |
Common Errors
- Reading a local from outside.
typeofreturns"undefined", and a direct read throwsReferenceError: x is not defined. Return the value, or declare the variable in the outer scope. - Expecting locals to persist between calls. Each call starts fresh. Move the state outward or into a closure.
- Assuming
varis block-scoped. Avarin aniforforis visible in the whole function. - Confusing reassignment with mutation. Reassigning a parameter is local. Mutating an object you were passed is not.
- Forgetting the declaration keyword. In sloppy mode,
total = 0inside a function with no declaration creates a global. A later chapter on accidental globals covers this.
Exercise
What does this code print, and why? function tally() { if (false) { var hits = 10; } return typeof hits; } console.log(tally()); console.log(typeof hits);
Show answer
It prints "undefined" twice, for different reasons. Inside tally, hits is declared, because var attaches to the whole function even inside a block that never runs. It was never assigned, so its value is undefined. Outside tally, no variable named hits exists, and typeof on an undeclared name also returns "undefined".
Exercise
A teammate writes function track(id) { let id = String(id); return id; } and gets an error before the code runs. Name the error, explain it, and give a fix that keeps the conversion.
Show answer
It is a SyntaxError: Identifier 'id' has already been declared. The parameter id is already a binding in the function scope, and let cannot declare the same name in that scope. Fix it by using a new name, such as const key = String(id); return key;, or by reassigning the parameter: id = String(id); return id;.
Exercise
What does demo() return? const y = 1; function demo(a = y + 1) { const y = 100; return a; }
Show answer
It returns 2. Because demo has a default parameter, its parameters are evaluated in a separate scope that cannot see the body's const y. The default expression y + 1 resolves y to the outer y, which is 1.