Sub topic 3
var and Function Scope
This chapter assumes you can write and call functions, use if statements and for loops, and run code in a browser console or Node.js. It also assumes you have read the previous chapter's description of global, function, and block scope. Here we look closely at one rule: a var declaration belongs to the nearest enclosing function, not to the block it is written in. Many surprises in older JavaScript code come from this rule.
The rule in one sentence
When the engine sees var name, it creates the variable in the scope of the closest function that contains the declaration. If no function contains it, the variable goes into the top-level scope of the script or module. Curly braces from if, for, while, switch, try, or a plain { } block do not limit a var.
function demo() {
if (true) {
var a = 1;
}
console.log(a); // 1: a belongs to demo(), not to the if block
}
demo();The if block looks like a container, but a is not inside it. a is a variable of demo, and the block only holds the line that assigns 1 to it.
What does create a scope for var
The table lists common constructs and whether they create a new scope for var.
| Construct | New scope for `var`? | Notes |
|---|---|---|
| Function declaration `function f() {}` | Yes | The usual boundary |
| Function expression `const f = function () {}` | Yes | Same as a declaration |
| Arrow function `() => {}` | Yes | Arrow bodies are function bodies |
| Object or class method `m() {}` | Yes | Methods are functions |
| `if`, `else`, `switch` | No | `var` passes straight through |
| `for`, `while`, `do...while` | No | Loop counters leak out |
| `try`, `catch`, `finally` | No | Only the catch parameter is block-scoped |
| Plain block `{ ... }` | No | Has no effect on `var` |
| Top level of a classic script | Global scope | Covered in a later chapter |
| Top level of an ES module | Module scope | Not visible to other modules |
The only boundary that matters is a function. A var inside a function never escapes that function. A var inside a block always escapes that block.
The function boundary holds
A function is a real wall for var. Code outside the function cannot see a variable declared inside it.
function outer() {
var secret = 'hidden';
return secret.length;
}
console.log(outer()); // 6
console.log(typeof secret); // 'undefined': secret does not exist out heretypeof returns 'undefined' for a name that was never declared, so it works as a safe probe. Writing console.log(secret) would throw a ReferenceError instead.
Nested functions follow the same rule. Each function gets its own var scope. An inner function can read variables from the functions around it, but its own var declarations stay inside it.
function outer() {
var shared = 'outer value';
function inner() {
var local = 'inner value';
console.log(shared); // 'outer value': inner can see outward
}
inner();
console.log(typeof local); // 'undefined': outer cannot see inward
}
outer();Shadowing
If an inner function declares a var with the same name as an outer one, the inner variable shadows the outer one. Inside the inner function, the name refers to the inner variable, and the outer variable is unchanged.
function outer() {
var level = 'outer';
function inner() {
var level = 'inner';
return level;
}
console.log(inner()); // 'inner'
console.log(level); // 'outer': untouched
}
outer();Shadowing only happens across a function boundary. Inside one function, a second var level written in a block does not create a second variable. It refers to the same one.
function outer() {
var level = 'outer';
if (true) {
var level = 'block'; // same variable, not a new one
}
console.log(level); // 'block'
}
outer();Many people expect this code to print 'outer', because they assume the block works like it does in C, Java, or with let. With var, the block has no scope of its own.
The variable exists even if the block never runs
The engine registers every var in a function before running the function body. So the variable exists across the whole function even when the line that declares it never runs.
function greet(flag) {
if (flag) {
var message = 'hello';
}
return message;
}
console.log(greet(true)); // 'hello'
console.log(greet(false)); // undefined, not a ReferenceErrorWith greet(false), the assignment never runs, but message was still created at the start of the call with the value undefined. This behavior is called hoisting. The hoisting chapter covers exactly when it happens. For now, the point is that the variable's scope is the whole function, from the first line to the last.
Loop counters leak
A for loop's counter declared with var belongs to the surrounding function. After the loop ends, the counter is still there with its final value.
function findFirstNegative(numbers) {
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] < 0) {
break;
}
}
return i; // i is still in scope here
}
console.log(findFirstNegative([4, 7, -2, 9])); // 2
console.log(findFirstNegative([1, 2, 3])); // 3 (equals the length: nothing found)Older code sometimes relied on this deliberately, as above. More often the leak is accidental. It also causes the well-known bug where closures created in a loop all see the same counter. That bug has its own chapter later.
The nested-loop bug
When two loops in the same function both use var i, they share one variable. The inner loop changes the outer loop's counter.
function pairs() {
var out = [];
for (var i = 0; i < 2; i++) {
for (var i = 0; i < 2; i++) {
out.push(i);
}
}
return out;
}
console.log(pairs()); // [0, 1] (you probably expected [0, 1, 0, 1])Here is how it runs. The outer loop sets i to 0. The inner loop resets the same i to 0, pushes 0 and 1, and exits when i is 2. Then the outer loop's i++ makes it 3, and 3 < 2 is false, so the outer loop stops after one pass. JavaScript reports no error and no warning. The fix is to use different names, or to use let, which gives each loop its own counter.
Parameters and var share a scope
Function parameters live in the same scope as the function's var declarations. Declaring a var with the same name as a parameter does not create a new variable.
function keep(x) {
var x; // no initializer: the parameter's value is kept
return x;
}
function overwrite(x) {
var x = 10; // the assignment replaces the parameter's value
return x;
}
console.log(keep(5)); // 5
console.log(overwrite(5)); // 10A var with no initializer does nothing to an existing variable. Only the = 10 part has an effect, and it acts as a normal assignment. With let x in the same place you would get a SyntaxError, which is one reason let catches more mistakes. The rules for redeclaration have their own chapter.
try and catch blocks
try, catch, and finally blocks are ordinary blocks, so a var inside them belongs to the function.
function parse(text) {
try {
var result = JSON.parse(text);
} catch (err) {
var problem = err.name;
}
return { result: result, problem: problem };
}
console.log(parse('{"ok":true}')); // { result: { ok: true }, problem: undefined }
console.log(parse('not json')); // { result: undefined, problem: 'SyntaxError' }The catch parameter err is the one exception. It is scoped to the catch block only, so err is not visible after the block, even though problem is.
Using function scope on purpose: the IIFE
Before let and const arrived in ES2015, a function was the only way to create a private scope. Developers wrapped code in an immediately invoked function expression (IIFE), which is a function that is defined and called in one step, so that its var declarations stayed private.
var counter = (function () {
var count = 0; // private: only the returned functions can reach it
return {
increment: function () {
count = count + 1;
return count;
},
current: function () {
return count;
}
};
})();
counter.increment();
counter.increment();
console.log(counter.current()); // 2
console.log(typeof count); // 'undefined'The parentheses around function () { ... } turn it into an expression, and the trailing () calls it right away. You will see this pattern in older libraries and in bundler output. In new code, a module or a plain block with let or const does the same job with less ceremony.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A variable has a value after the `if` block that set it | `var` belongs to the function, not the block | Use `let` or `const` so the variable stays in the block |
| A function returns `undefined` where you expected a `ReferenceError` | The `var` was registered, but its assignment did not run | Declare and initialize at the top, or use `let` |
| An outer loop stops early | Nested loops share one `var` counter | Use distinct names or `let` |
| A value set in a block overwrites one set earlier | A second `var` with the same name in the same function | Rename it, or use `let` to get a `SyntaxError` instead |
| A parameter's value is unexpectedly replaced | `var param = ...` inside the function assigns to the parameter | Choose a different local name |
Exercises
Exercise
What does this code print, and why? function run() { var total = 1; { var total = 2; } function helper() { var total = 3; } helper(); console.log(total); } run();
Show answer
It prints 2. The plain block does not create a scope for var, so var total = 2 refers to the same variable as var total = 1 and overwrites it. The var total = 3 inside helper() is in a separate function scope, so it shadows the outer total only inside helper and does not change the value that run() logs.
Exercise
The function below should return true if any word in the list is longer than 5 characters, but for ['hi', 'wonderful'] it returns undefined instead of true, and for ['hi'] it returns undefined instead of false. Explain why it does not throw, and rewrite it so it always returns a boolean. function hasLongWord(words) { for (var i = 0; i < words.length; i++) { if (words[i].length > 5) { var found = true; } } return found === true ? found : undefined; }
Show answer
found is a var, so it belongs to the whole function and exists from the start of the call with the value undefined. Returning it never throws, even when the line var found = true never runs. The return line itself is also faulty: it returns undefined whenever found is not true. A correct version declares the result up front: function hasLongWord(words) { let found = false; for (let i = 0; i < words.length; i++) { if (words[i].length > 5) { found = true; } } return found; }. This returns true for ['hi', 'wonderful'] and false for ['hi'].
Exercise
Without running it, predict the output of console.log(pairs()) if the inner loop in the nested-loop example is changed to for (var j = 0; j < 2; j++) { out.push(j); }. Then explain why renaming the variable fixes the bug even though both variables are still function-scoped.
Show answer
It prints [0, 1, 0, 1]. i and j are both function-scoped, but they are now two separate variables. The inner loop resets and increments only j, so the outer loop's i goes 0, 1, 2 as intended and the inner loop runs twice.