Sub topic 3
Function Scope
This chapter assumes you can write and call functions and declare variables with var, let, and const. It also assumes you know that lexical scope means visibility is decided by where code is written, and that the global scope is the outermost level.
Every Function Creates a Scope
A function body is a scope. Anything declared inside it is local to that function. That covers parameters, var, let, and const declarations, and nested function declarations. Code outside the function cannot see those names.
function calculateTotal(price, quantity) {
var taxRate = 0.25;
const subtotal = price * quantity;
return subtotal * (1 + taxRate);
}
console.log(calculateTotal(10, 2)); // 25
console.log(typeof taxRate); // "undefined"
try {
console.log(subtotal);
} catch (e) {
console.log(e.name); // "ReferenceError"
}price, quantity, taxRate, and subtotal exist only while calculateTotal runs. Outside the function, subtotal was never declared, so reading it throws a ReferenceError. typeof doesn't throw for undeclared names, so typeof taxRate reports "undefined".
Visibility Goes One Way
A function can read variables from the scopes that surround it. The surrounding code cannot read the function's local variables.
const siteName = "Docs";
function greet(user) {
const message = "Welcome to " + siteName + ", " + user;
return message;
}
console.log(greet("Ana")); // "Welcome to Docs, Ana"
console.log(typeof message); // "undefined"The next chapter on the scope chain explains how that outward lookup works step by step.
Each Call Gets Fresh Variables
A function's scope is created again on every call. Local variables don't keep their values between calls.
function tally() {
let count = 0;
count += 1;
return count;
}
console.log(tally()); // 1
console.log(tally()); // 1Developers sometimes expect count to keep growing. It can't, because each call starts with a new count. To keep state across calls, either declare the variable outside the function or use a closure, which a later chapter covers.
var Belongs to the Function, Not the Block
var is scoped to the whole enclosing function. An if block or a loop body inside the function does not limit it.
function check(flag) {
if (flag) {
var message = "set inside if";
}
return message;
}
console.log(check(true)); // "set inside if"
console.log(check(false)); // undefinedmessage is visible across all of check, even outside the if. When flag is false, it holds undefined instead of throwing. The next chapter shows how let and const behave differently. The hoisting chapters explain why the value is undefined.
Using Function Scope for Privacy
Before modules existed, developers wrapped code in an immediately invoked function expression (IIFE) to keep helper variables out of the global scope.
const config = (function () {
var secret = "abc123";
return { hasSecret: secret.length > 0 };
})();
console.log(config.hasSecret); // true
console.log(typeof secret); // "undefined"secret is local to the IIFE, so other scripts can't overwrite it or collide with it.
Common Errors
| Mistake | Result | Fix |
|---|---|---|
| Reading a local variable outside its function | `ReferenceError` | Return the value or declare it in the outer scope |
| Expecting locals to persist between calls | Value resets each call | Store state outside the function or in a closure |
| Assuming `var` in an `if` is limited to the block | Variable leaks across the function | Use `let` or `const` |
Exercise
What does this code print, and why? function setup() { var ready = true; } setup(); console.log(typeof ready);
Show answer
It prints "undefined". The variable ready is declared with var inside setup, so it is local to that function's scope. After setup returns, the global scope has no binding named ready, and typeof returns "undefined" for undeclared names instead of throwing.
Exercise
A function runs let attempts = 0; attempts++; return attempts; and is called three times. What does the third call return, and how could you make it return 3?
Show answer
It returns 1, because every call creates a fresh scope with a new attempts set to 0. To get 3, declare attempts outside the function (or capture it in a closure) so all calls share the same variable.