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 builds on the previous chapter's idea that scope is the region of code where a name can be used.
The Rule: var Belongs to the Function
A variable declared with var is scoped to the nearest enclosing function. If there is no enclosing function, it is scoped to the whole script. Curly braces from if, for, while, or a bare { } block do not create a new scope for var. The block is invisible to it.
function checkout(items) {
if (items.length > 0) {
var message = 'Processing ' + items.length + ' items';
}
console.log(message);
}
checkout(['apple', 'pear']); // Processing 2 items
checkout([]); // undefinedThe message variable is declared inside the if block, but it belongs to checkout as a whole. In the second call the if body never runs. message still exists, though, and its value is undefined. The next chapter on hoisting explains why it is undefined rather than an error.
Each Function Gets Its Own Scope
Functions are the boundary var respects. A nested function has its own scope, so a var inside it does not touch the outer variable with the same name. Code outside the function cannot see either one.
function outer() {
var level = 'outer';
function inner() {
var level = 'inner'; // a separate variable, local to inner
console.log(level); // inner
}
inner();
console.log(level); // outer
}
outer();
try {
console.log(level);
} catch (e) {
console.log(e.name); // ReferenceError
}This is the one form of isolation var gives you. Before let and const existed, developers made their own private scopes by wrapping code in an immediately invoked function expression (IIFE):
(function () {
var secret = 42;
console.log(secret); // 42
})();
console.log(typeof secret); // 'undefined'You will still see this pattern in older libraries and bundled code.
Common Errors
Loop counters leak out of the loop
A for (var i ...) counter is a function-scoped variable and stays alive after the loop ends. Some older code relies on this on purpose:
function findIndex(list, target) {
for (var i = 0; i < list.length; i++) {
if (list[i] === target) break;
}
return i; // i is still in scope here
}
console.log(findIndex(['x', 'y', 'z'], 'y')); // 1
console.log(findIndex(['x', 'y', 'z'], 'q')); // 3This works, but readers can easily misread it, and it leaves i available for accidental reuse later in the function.
Reusing a name in a block silently overwrites it
Since a block does not create a new var scope, declaring the "same" variable again inside a block just refers back to the existing one. JavaScript reports no error and gives no warning.
function report(scores) {
var total = 0;
for (var k = 0; k < scores.length; k++) {
total += scores[k];
}
if (scores.length > 3) {
var total = 'many scores'; // same variable as above
}
return total;
}
console.log(report([1, 2, 3])); // 6
console.log(report([1, 2, 3, 4])); // 'many scores'The author may have meant to create a temporary variable inside the if. Instead, they replaced the sum.
Summary Table
| Where `var` is declared | Where it is visible |
|---|---|
| Inside an `if`, `for`, or `{ }` block | The entire enclosing function |
| Inside a function | That function and any functions nested in it |
| Inside a nested function | Only the nested function |
| Outside any function | The whole script (global scope) |
The next chapter covers let and const, which do respect blocks and avoid both of the errors above.
Exercise
What does this code print, and why? function test() { var x = 'a'; if (true) { var x = 'b'; var y = 'c'; } console.log(x, y); } test();
Show answer
It prints "b c". Both declarations of x refer to the same function-scoped variable, so the assignment inside the if block overwrites 'a' with 'b'. The variable y is also scoped to test, not to the if block, so it is visible to console.log.
Exercise
You want a variable named temp that exists only inside a block, and you are restricted to var. How can you keep it from being visible to the rest of the function?
Show answer
Wrap the code in a function, for example an IIFE: (function () { var temp = 1; / use temp / })(); Since var respects only function boundaries, a new function is the only way to give it a private scope.