Analyzing Variable Scope and Execution Flow
Six habits for reading code. Free to watch, with a free slide PDF and practice questions.
Chapters
- 0:00 Analyzing Variable Scope and Execution Flow
- 0:47 Quick recap: how modules share code
- 1:31 Six habits for reading code
- 2:14 One table holds the whole lesson
- 3:41 A name is looked up outward, one scope at a time
- 5:02 var ignores blocks; let and const respect them
- 6:16 Before the declaration line, three things can happen
- 7:18 An inner const hides the outer one from the first line
- 8:03 A closure keeps the variable alive
- 9:01 var shares one variable; let makes one per iteration
- 9:53 this is decided by how the function is called
- 10:46 Arrow functions and bind do not take a new this
- 11:31 The call stack runs first; queued jobs wait
- 12:31 A zero delay does not mean now
- 13:18 if and switch decide the path; fall-through bites
- 14:15 finally always runs, and its return wins
- 15:18 The return in try is not the last word
- 15:54 Six terms to say in your own words
- 16:35 Trace each program on paper, then run it in Node
- 18:00 Eight questions, closed book
- 19:15 A developer runs this code. What is logged?
- 20:05 finally
- 20:47 Six rules, six traps
- 21:31 Now test it, then move to the browser
Test yourself on analyzing variable scope and execution flow
Practice questions for this lesson come with a full explanation of why each answer is right or wrong, and link back to the exact moment in the video.
Take the free diagnosticTranscript
Read the full lesson text
Analyzing Variable Scope and Execution Flow 0:00
Welcome to module two, lesson five: analyzing variable scope and execution flow. This module is called Objects, Functions, and Classes, and it carries twenty five percent of the exam. In this lesson we read code the way the engine does. Scope tells us which variables a line of code can see. The keyword this tells us which object a function is working on. And finally decides what runs last, no matter what came before it. Every question in this lesson shows you code and asks what it logs, so reading carefully is the whole skill. By the end, you will be able to read a block of code from top to bottom, and say which variables are visible, what this is, and the exact order of the output.
Quick recap: how modules share code 0:47
Before we start, a quick recap from lesson four, on JavaScript modules. First, a module can have many named exports, but only one default export. Second, imports are live, read only bindings. The importer can read them, but it cannot reassign them. Third, a browser needs the type attribute set to module on the script tag, and dynamic import returns a promise. And fourth, Node chooses between the two module systems by the file extension, or by the package json file. Those lessons were about how code is shared between files. Today we move from sharing code to reading code: which variables a line can see, and in what order the code runs.
Six habits for reading code 1:31
This domain is twenty five percent of the exam. This lesson boils down to six habits for reading code, and there are five traps to spot along the way. First, follow the scope chain. Second, read top down, because of hoisting. Third, remember that closures hold variables. Fourth, this comes from the call site. Fifth, the order is synchronous code, then microtasks, then timers. And sixth, finally always runs. Closures, hoisting, and finally produce most of the questions, so we slow down there. We will also cover the call stack, if and switch, and the temporal dead zone, which we explain when we reach hoisting.
One table holds the whole lesson 2:14
This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Scope. The rule is to look outward, never inward. The trap is that var ignores blocks. The safe habit is to prefer let and const. Hoisting. The rule is that declarations are known first. The trap is that let and const sit in the temporal dead zone until their line runs. The safe habit is to declare before use. Closure. The rule is that it holds the variable itself. The trap is that var in a loop gives three, three, three. The safe habit is to use let in loops. This. The rule is that it is set by how the function is called. The trap is that a detached method loses it. The safe habit is to read the call site. Order. The rule is synchronous code, then microtasks, then timers. The trap is that "set timeout" with a delay of zero still runs last. The safe habit is to trace it on paper. Finally. The rule is that it runs after try and catch. The trap is that its return wins. The safe habit is to never return inside it. One practical rule to carry with you: read the code the way the engine does, one scope and one call at a time.
A name is looked up outward, one scope at a time 3:41
Habit one: a name is looked up outward, one scope at a time. Look at the code. A constant e is ten, at the top. Then sum takes a, and returns a function that takes b. That one returns a function that takes c. The innermost function returns a plus b plus c plus e. Calling sum of one, then two, then three, logs sixteen. Let us trace the lookup. When the innermost function needs a, it is not in its own scope, so JavaScript steps outward. It checks the function that took b, then the function that took a, and finds a there. The name e is not in any of them, so the search ends at the global scope, where e is ten. Scope is lexical. Where the code is written decides what it can see, not where it is called from. To find a name, JavaScript looks in the current scope, then the enclosing one, and keeps going outward to global. That list of enclosing scopes is the scope chain. So the innermost function sees a, b, c, and e. Inner scopes can read outer variables, but outer scopes never read inner ones. The outer function has no way to see c. The exam point: sum of one, two, three is sixteen. That is one plus two plus three, plus the ten outside.
var ignores blocks; let and const respect them 5:02
Not every block makes a scope for every keyword. There are three kinds of scope: global, function, and block. And var ignores blocks, while let and const respect them. Look at the code. Inside an if block, we declare var a as one, and const b as two. After the block, console dot log of a prints one, because var ignored the block. But the "type of" check on b prints the string undefined, because b only existed inside the braces. Here is the trace. The block ends, and b is gone. The variable a was attached to the whole function, or to global, so it is still there. The keyword var lives in the whole function, or in global if it is outside any function. Let and const live only in their block. The braces of an if or a for create a scope only for let and const. For var, they are just punctuation. Reading b outside its block throws a "reference error". The "type of" check avoids that error, and returns the string undefined instead. The exam point: a var in an if or for block is visible after it. A let or const is not.
Before the declaration line, three things can happen 6:16
Habit two: read top down. Before a declaration line, three different things can happen, and you need to know which. Look at the code. On the first line, console dot log of v prints undefined, even though var v is five comes next. And greet is called before its function declaration, yet it prints the string Hello. A function declaration works before its line, because the whole function is known early. A var reads undefined. The declaration is known early, but the assignment has not happened yet. Let, const, and class throw a "reference error" if you touch them before their line. That gap, before initialization, is the temporal dead zone, or T D Z for short. The name exists, but you may not use it yet. When you read code, go line by line and ask what exists at this point. That one question solves most hoisting puzzles. The exam point: function works, var is undefined, let and const throw.
An inner const hides the outer one from the first line 7:18
Here is a trap that catches careful readers. The wrong shortcut says, it prints one, from the outer x. It feels natural: an x with the value one is sitting right above. The correct exam test: the inner const x covers the whole block, so the earlier read hits the T D Z. Look at the code. The outer x is one. Inside the braces, console dot log of x comes first, and the const x is two comes after it. The declaration is hoisted to the top of the block, but it is not initialized, so the log throws a "reference error". It never reaches the outer x. The practical rule: find every declaration in a block before you decide which name a line reads.
A closure keeps the variable alive 8:03
Habit three: a closure keeps the variable alive. Look at the code. "Make counter" creates a variable n, starting at zero, and returns an arrow function that adds one to n. We call "make counter" once, and store the result in c. Then we call c three times, and the last call prints three. Let us trace it. The first call to c makes n one. The second makes it two. The third makes it three, and that is the value logged. The same n was updated each time. A function keeps a reference to its lexical environment. That holds even after the outer function has returned. So n lives on, because the arrow function still uses it. Each call to "make counter" makes its own separate n. Two counters never share their count. And closures capture block scoped variables too. The exam point: closures capture variables, not copies of values.
var shares one variable; let makes one per iteration 9:01
The classic closure trap lives in loops. The wrong shortcut says, each callback remembers its own i. The correct exam test: with var there is one i. By the time the callbacks run, it holds the last value. Look at the first block. A loop with var i pushes three arrow functions into an array. All three read the same i. The loop ends when i reaches three, so mapping over the functions gives three, three, three. In the second block, let j makes a new variable for each iteration. Each arrow function keeps its own j, so the result is zero, one, two. The same holds for "set timeout" callbacks created in a loop. If they run later, a var gives them all the final value. The practical rule: use let in a loop whose callbacks run later.
this is decided by how the function is called 9:53
Habit four: this is decided by how the function is called, not by where it is written. Look at the code. The object o has a name, the string o, and a method reg that returns this dot name. We copy the method into f. Calling o dot reg gives the string o. But f dot call, with an object named x, gives the string x. So it is the same function, called two ways, with two different answers. When you call obj dot f, this is the object. A plain call, f with nothing before it, gives "global this" in sloppy mode, and undefined in strict mode. A method copied to a variable loses its object. The copy has no object in front of it when you call it. And call and apply set this for that one call. The exam point: look at the call site, not the definition.
Arrow functions and bind do not take a new this 10:46
Two more things that do not take a new this. The wrong shortcut says, call can always change this. The correct exam test: an arrow keeps the this of where it was created, and bind fixes this for good. Look at the code. We bind the method to an object named a. Then calling bound dot call, with an object named b, still gives the string a. Bind wins. And an arrow function uses the enclosing this, whatever call, apply, or bind says. Think of an arrow as having no this of its own. It simply looks outward, just like a variable lookup. The exam point: class code is strict, so a detached class method has this undefined.
The call stack runs first; queued jobs wait 11:31
Habit five: the call stack runs first, and queued jobs wait. Look at the code. First it logs A. Then a timer with zero delay will log B. Then a resolved promise will log C. And last it logs D. The output is A, D, C, B. Here is the trace. A and D are synchronous, so they run straight away, in order. C is a microtask, so it runs as soon as the current code is finished. B is a macrotask, so it waits until every microtask is done. The call stack is last in, first out. A call pushes a frame, and a return pops it. A running job finishes before another starts. Nothing interrupts it halfway. Then all microtasks run: promise handlers, and the code after await. Only then does a "set timeout" callback run, even with a delay of zero. The exam point: output order is synchronous code, then promise callbacks, then timers.
A zero delay does not mean now 12:31
A zero delay does not mean now. The wrong shortcut says, "set timeout" with zero runs right away. The correct exam test: it waits for the current code, and for every queued microtask. Look at the code. The timer logs one, the promise logs two, and the plain log prints three. Trace it: three runs now, because it is synchronous. Then the promise handler prints two. Only then does the timer print one. So the output is three, two, one. The event loop keeps draining microtasks until none are left. That means a microtask that queues another microtask does not let the timer in either. The exam point: a microtask that queues another microtask still runs before the next timer.
if and switch decide the path; fall-through bites 13:18
Next, how if and switch decide the path through the code. Look at the code. We switch on two. Case one would log one, but it does not match. Case two matches, and logs two. There is no break there, so case three runs too, and logs three. Then break stops the switch, so default never runs. The output is two, three. This is called fall-through, and it is the part of switch that bites. The falsy values are false, undefined, null, zero, nan, and the empty string. Everything else is truthy, including every object. Without break, a switch continues into the next case. And new Boolean of false is an object, so it is truthy. Condition checks in an if use truthiness, not strict equality. The exam point: a matching case runs, and so does every case below it until a break.
finally always runs, and its return wins 14:15
Habit six: finally always runs, and its return wins. Look at the code. The function f tries to log zero, and then throws the string bogus. The catch block logs one, and returns true. But the finally block logs three, and returns false. Then we log the result of calling f. So the console shows zero, one, three, and then false. Let us trace it step by step. The throw jumps straight to catch, so the rest of try is skipped. Catch logs one, and its return of true is now pending. Before the function can really return, finally runs. It logs three, and returns false, which replaces the pending value. A throw in try jumps straight to catch. Finally runs after try and catch, before the code that follows. It runs even after a return in try or catch. And a return in finally replaces a pending return or throw. The exam point: finally runs even after return, and a return inside it wins.
The return in try is not the last word 15:18
One more trap, from the same habit. The wrong shortcut says, try returns first, so the function ends there. The correct exam test: finally runs before the function actually returns, and it may replace the value. Look at the code. Try throws an error. Catch would return the string catch. But finally returns the string finally. So g returns the string finally, and the thrown error is discarded too. Nothing is ever reported. The practical rule: scan for finally before you trust any return or throw above it.
Six terms to say in your own words 15:54
Six terms to say in your own words. Lexical scope is visibility decided by where a variable is declared in the source. Scope chain is the list of enclosing scopes searched outward for a name. A closure is a function plus references to its surrounding variables. Hoisting and the T D Z: declarations are known early, but let and const throw until they are initialized. The call stack is the last in, first out stack of function frames. And a microtask is a promise style job that runs before the next timer. Pause the video now. Cover each card and explain the term aloud. If you stumble on one, go back to its slide.
Trace each program on paper, then run it in Node 16:35
Now the proof stage, starting with a lab. Trace each program on paper, then run it in Node. You have five small programs on screen. For each one, write down the scope chain and the call stack, and then the output. Do it before you check. Take three minutes on your own, and write down your predictions before checking. Now the answers, one program at a time. Program one: var a is one inside a block, and let b is two. Logging a gives one, and the "type of" b is the string undefined, because b stayed inside the braces. Program two: calling f before its declaration works and gives one. And v is undefined, because only the declaration of v is hoisted, not the value. The output is one, undefined. Program three: a loop with let. The first function returns zero, and the third returns two, because each iteration has its own i. The output is zero, two. Program four: the timer, the promise, and the plain log. The plain log runs first, then the promise, then the timer. The output is three, two, one. Program five: try returns one, but finally returns two. Finally runs last, so the output is two. A wrong prediction is the lesson. Go back to the slide that explains it.
Eight questions, closed book 18:00
Self check: eight questions, closed book. Answer out loud, then I will reveal each one. One. After a block that declares var a as one, what does logging a give? The number one. Two. After a block that declares const b, what does the "type of" b give? The string undefined. Three. What does logging v give, before var v is five? Undefined. Four. A counter is called three times. What do the three calls give? One, two, three. Five. A var loop pushed three closures that read i. What does mapping over them give? Three, three, three. Six. One log of A, a timer for B, a promise for C, and a log of D. In what order do they print? A, D, C, B. Seven. A method is bound to a, then called with b. What is this? It is a. And eight. Try returns one, and finally returns two. What does the function give? Two. How many did you get? Anything you missed, go back to its slide.
A developer runs this code. What is logged? 19:15
Time for a practice question, taken from the question bank. This is a predict question. Pause the video and trace try, catch, and finally in order before you read the options. A developer runs this code. The function g tries to throw an error. Its catch returns the string catch. Its finally returns the string finally. Then we log the result of calling g. What is logged? Option A: the string finally. Option B: the string catch. Option C: undefined. Option D: an uncaught error with the message x. This question combines try, catch, and finally. Work through the three blocks one at a time. Pause now, and I will give you the answer on the next slide.
finally 20:05
The answer is A. The string finally. Here is why. The throw goes to catch. The catch return is pending, holding the string catch. Then finally runs, and returns its own value, which wins. Now the wrong options. B says catch. That return is pending, but finally replaces it. C says undefined. But every path returns a string, so undefined is not possible. D says an uncaught error. But catch handles the error, and the return in finally discards anything pending anyway. The takeaway: finally always runs, and a return inside it wins.
Six rules, six traps 20:47
Let's consolidate. Six rules, six traps. Scope: look outward. Var ignores blocks, but let and const do not. Hoisting: a function works, var is undefined, and let and const throw. Closure: it holds the variable. A var loop gives three, three, three. This: set by the call site. Arrows and bind keep theirs. Order: synchronous code, then microtasks, then timers. Finally: it always runs, and its return wins. Remember: read top down, trace the call, and check for finally. If you can say these six from memory, you've got the lesson.
Now test it, then move to the browser 21:31
That completes lesson five. Now test it, then move to the browser. The flow is: read it, trace it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next module we move to the browser. The next lesson is Events, Handlers, and Propagation, where we see how an event travels through the page. See you there.