So far, every value Marco’s scoring helpers needed came in through a parameter. You traced those calls on the call stack: each call got its own frame, stacked in the order the calls ran. As his kit grows, though, Marco’s helpers use names they never declared, like a round name.
Where does JavaScript look for a name like that? You’ll learn the rule it follows, so you can point at any name in nested code and say which declaration it reaches. You’ll also see why the function that made a call has no say in it. Start with a helper that reads two names it didn’t declare.
Walk Outward to Find a Name
A helper written inside another function often needs that function’s values, and passing each one as an argument gets tedious. Here’s Marco’s round report, where formatLine() sits inside printRoundReport():
round_report.js
const pubName = "The Lantern";
function printRoundReport(roundName, teams) {
const maxPoints = 10;
function formatLine(team) {
const points = `${team.points}/${maxPoints}`;
return `${team.name}: ${points} in ${roundName}`;
}
for (const team of teams) {
console.log(formatLine(team));
}
console.log(`Scored at ${pubName}`);
}
printRoundReport("Music", [
{ name: "The Lamplighters", points: 8 },
{ name: "Know-It-Owls", points: 0 },
]);
Run it, and every name finds its value:
$ node round_report.js
The Lamplighters: 8/10 in Music
Know-It-Owls: 0/10 in Music
Scored at The Lantern
Each function body and each block is a scope, and the scopes nest like boxes, exactly as the code is indented. The picture has one limit. The braces draw the boxes, and the indentation only helps you see them. A function’s parameters and a for loop’s const declaration sit before the braces but belong to the box that follows.
To find a name, put your finger on it and walk outward, one box at a time, until you reach a declaration. Start from maxPoints in formatLine(). The walk finds no declaration in the box for formatLine(), so it steps out into printRoundReport(), where maxPoints is declared. You find roundName in the same place, as a parameter. For pubName in printRoundReport(), the walk steps out to the file’s top level.
This rule is called lexical scope. “Lexical” means “about the text,” so the written code decides what a name refers to. The chain of boxes the walk passes through is the scope chain. You can read more in MDN’s Scope glossary entry.
Two consequences follow from the walk going outward only. If formatLine() declares its own const roundName, the walk stops there first. That separate inner variable shadows the outer one, which keeps its value. Code outside a function can never see in. Even after printRoundReport() has run, a top-level console.log(maxPoints) throws ReferenceError: maxPoints is not defined.
For practice, the button below opens a chat with your mentor, who sets a short puzzle and checks your trace of each name.
Reach the End of the Chain
What happens past the file’s top level? Nothing in the report above declares console, yet the call works.
After the top level, the walk makes one last stop at globalThis, the global object, which holds JavaScript’s built-ins, such as Math, and what Node.js adds, such as console. If the name isn’t there either, you get a ReferenceError.
The top level and globalThis are different stops. Because Node.js runs each file as its own module, declaring a name at the top of your file doesn’t add it to globalThis, whether you use const, let, or a function declaration. This file checks all three:
global_check.js
const pubName = "The Lantern";
let roundCount = 5;
function announceWinner() {}
console.log(`pubName: ${globalThis.pubName}`);
console.log(`roundCount: ${globalThis.roundCount}`);
console.log(`announceWinner: ${globalThis.announceWinner}`);
console.log(`console: ${typeof globalThis.console}`);
Only the built-in is a property of globalThis:
$ node global_check.js
pubName: undefined
roundCount: undefined
announceWinner: undefined
console: object
Your file’s names stay in its top-level scope, the module’s scope, and you’ll learn more about modules later. The REPL, an interactive Node.js prompt you’ll use next, isn’t a module file, so a top-level function typed there does land on globalThis. That’s all you need about the difference for now.
Ignore Who Made the Call
The walk follows where code is written, but the call stack follows who calls whom. Which one wins when they disagree? Marco wants one announce() helper for every round, with “Warm-Up” as the opening round, and a function that runs the music round:
announce.js
const roundName = "Warm-Up";
function announce() {
console.log(`Round: ${roundName}`);
}
function runMusicRound() {
const roundName = "Music";
announce();
}
announce();
runMusicRound();
When runMusicRound() calls announce(), the frame for runMusicRound() sits right below the frame for announce() on the stack, with roundName set to “Music”. Before you run the file, predict the second line it prints.
Both lines show the opening round:
$ node announce.js
Round: Warm-Up
Round: Warm-Up
Do the finger walk from roundName inside announce(). Its own box has no roundName, and the next box out is the file’s top level, where announce() is written. The walk never enters runMusicRound(), so its “Music” stays invisible. The stack records who called announce(), but name lookup never consults it.
A short REPL session confirms that the function’s position is what counts. Type node on its own in your terminal to start one, then type each line without its > or ... prompt. Node.js shows ... while a function’s braces are still open. This time, write announce() inside runMusicRound():
> const roundName = "Warm-Up";
undefined
> function runMusicRound() {
… const roundName = "Music";
… function announce() {
… console.log(`Round: ${roundName}`);
… }
… announce();
… }
undefined
> runMusicRound()
Round: Music
undefined
The undefined lines are the REPL reporting that a statement or call produced no value. The walk from roundName steps out of announce() into runMusicRound() and finds “Music” first. The call is the same as before. Only the place where announce() is written differs. Type .exit to leave the REPL and get back to your terminal.
Moving the helper inside works, but then each round function would need its own copy, and Marco wants a single announce(). The other fix passes the round name in as an argument:
announce.js
function announce(roundName) {
console.log(`Round: ${roundName}`);
}
function runMusicRound() {
const roundName = "Music";
announce(roundName);
}
announce("Warm-Up");
runMusicRound();
Now each caller hands over the name it means:
$ node announce.js
Round: Warm-Up
Round: Music
When a function needs a value from its caller, the caller passes it. When it needs a value from where it’s written, it reads it from an enclosing scope.
To check that you can keep the two models apart, use the button below to open a chat. The mentor has you explain in your own words why the first announce.js printed Warm-Up twice, then gives feedback.
Check Your Understanding
Try these before you open the answers.
-
Kwame wants one line per team for a round. Write
roundLines(roundName, teams), which returns an array of strings such as"Know-It-Owls: 7 in Music". Use.map()with an arrow callback that takes only a team and readsroundNamefromroundLines(). Run it on two teams, then say where the callback findsroundName. -
Diego wants to print the best round of his team, Second Guessers, but running this code throws a
ReferenceError. Explain why, and give two ways to fix it:
best_round.js
function formatBest(teamName) {
return `${teamName}'s best round: ${best}`;
}
function reportBest(team) {
const best = Math.max(...team.rounds);
console.log(formatBest(team.name));
}
reportBest({ name: "Second Guessers", rounds: [5, 9, 7, 4, 6] });
For the first question, here’s one solution, with Kwame’s and Mei’s teams:
round_lines.js
function roundLines(roundName, teams) {
return teams.map(
(team) => `${team.name}: ${team.points} in ${roundName}`
);
}
console.log(roundLines("Music", [
{ name: "Know-It-Owls", points: 7 },
{ name: "Table Six", points: 9 },
]));
Running it prints the array of lines:
$ node round_lines.js
[ 'Know-It-Owls: 7 in Music', 'Table Six: 9 in Music' ]
The callback is written inside roundLines(), so the walk from roundName steps out into roundLines(), where it’s a parameter. It doesn’t matter that .map() is the one calling the callback.
For the second question, calling reportBest() on the last line makes formatBest() run and look up best, which triggers the error:
$ node best_round.js
...
ReferenceError: best is not defined
formatBest() is written at the top level, so the walk from best goes straight there and never enters reportBest(), its caller. Either pass the value in with formatBest(team.name, best) and a second parameter, or move formatBest() inside reportBest(), where the walk finds best. Passing it in keeps one helper that any function can use.
Every name your examples found was declared above the line that used it. In the next lesson, Use Names Before Their Line, you’ll see what happens when code uses a name before its declaration.