Lesson 4 of 199:07 video

JavaScript closures and scope

Three ways to write a function, where a variable lives, how a closure keeps one alive after its function has returned, what a function can do with another function, and why a function that calls itself can run out of stack.

In this lesson

  1. 0:00 Intro
  2. 1:03 Writing a function
  3. 3:26 Scope
  4. 4:49 Closures
  5. 6:09 Functions that take functions
  6. 7:01 Recursion
  7. 8:30 Next time

Here’s a function that makes a countdown you can run one step at a time:

function makeCountdown(from) {
  let seconds = from;
  return function () {
    console.log(seconds);
    seconds = seconds - 1;
  };
}

const tick = makeCountdown(3);
tick(); // 3
tick(); // 2
tick(); // 1

The number is kept in seconds, a variable inside makeCountdown. But makeCountdown finished running before tick was called even once. The function that made the variable is done, and the variable is still there, still counting.

To see how a variable can outlive the function that made it, we need three things: the ways to write a function, the rules for where a variable lives, and what a function carries with it.

Three ways to write a function

Function declarations

The keyword function, a name, and a body. This is a function declaration:

function half(seconds) {
  return seconds / 2;
}

Function expressions

A function is a value, like a number or a string. So you can write one without a name and store it in a constant. This is a function expression:

const half = function (seconds) {
  return seconds / 2;
};

Both give you a function called half, and both are called the same way. The difference shows when the call comes before the definition. JavaScript sets up function declarations before it runs the first line, so a call above one works:

console.log(half(10)); // 5

function half(seconds) {
  return seconds / 2;
}

A constant doesn’t exist until its own line runs, so the same call is an error:

console.log(half(10)); // ReferenceError: Cannot access 'half' before initialization

const half = function (seconds) {
  return seconds / 2;
};

Arrow functions

The third way arrived in 2015, and it’s the one you’ll see most. An arrow function drops the keyword: parameters in parentheses, then an arrow (=>), then the body.

const half = (seconds) => {
  return seconds / 2;
};

When the body is one expression, you can drop the braces and the return. Whatever the expression works out to is what comes back:

const half = (seconds) => seconds / 2;

With exactly one parameter, the parentheses can go too:

const half = seconds => seconds / 2;

All of these versions of half give 5 for half(10). Declarations suit the named functions your program is built from. Arrow functions suit the small ones you hand to other functions.

Parameters and default values

A parameter is a variable that gets its value from the call. JavaScript never checks how many values you send.

function countdown(from) {
  for (let seconds = from; seconds > 0; seconds = seconds - 1) {
    console.log(seconds);
  }
  console.log("Liftoff");
}

countdown(3);     // 3, 2, 1, Liftoff
countdown();      // Liftoff
countdown(3, 99); // 3, 2, 1, Liftoff

Call countdown with nothing, and from is undefined. There’s no error. The loop compares undefined with zero, gets false, and the program prints only Liftoff. Send two values, and the extra one is ignored.

Since 2015, a parameter can have a default: an equals sign and a value after its name, used whenever the call leaves that value out.

function countdown(from = 10) {
  for (let seconds = from; seconds > 0; seconds = seconds - 1) {
    console.log(seconds);
  }
  console.log("Liftoff");
}

countdown(); // 10, 9, 8 ... 1, Liftoff

Scope: where a variable lives

Every variable has a scope: the stretch of code where its name means something.

  • A variable declared outside every function is global. The whole program can see it.
  • A variable declared inside a function is local. Only that function can see it, it’s created fresh with every call, and normally it’s thrown away when the function returns.
const planet = "Mars"; // global

function countdown(from) {
  let seconds = from;  // local
  console.log(planet); // works: inside can look outside
}

countdown(3);
console.log(seconds); // ReferenceError: seconds is not defined

Inside can look outside: the function reads planet without trouble. Outside can’t look inside: ask for seconds after the call, and JavaScript says it’s not defined. Parameters are local too, so from exists only during the call.

Block scope, and why new code avoids var

Since 2015, the curly braces of an if or a loop make a scope as well, for let and const. The seconds in this loop exists only inside the loop:

for (let seconds = 3; seconds > 0; seconds = seconds - 1) {
  console.log(seconds);
}
console.log(seconds); // ReferenceError: seconds is not defined

var ignores the braces. Declare the variable with var, and it leaks out of the loop:

for (var seconds = 3; seconds > 0; seconds = seconds - 1) {
  console.log(seconds);
}
console.log(seconds); // 0

var also lets you read a variable above the line that declares it. You get undefined instead of an error, so a mistake in the order of your lines stays quiet. let does the opposite and stops with an error:

console.log(a); // undefined
var a = 1;

console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 1;

That’s why new code uses let and const, and reads var as the old way.

Closures

Back to makeCountdown, the function this lesson opened with:

function makeCountdown(from) {
  let seconds = from;
  return function () {
    console.log(seconds);
    seconds = seconds - 1;
  };
}

Inside makeCountdown there’s a variable, seconds, and a function that uses it. The inner function can see seconds because inside can look outside.

Look at what it does with seconds. It doesn’t take a copy of the number. It keeps a link to the variable itself, and every call reads and changes that same variable.

A function carries the scope it was created in, wherever it goes. Return it, store it, hand it to someone else, and the link comes along.

A function together with the variables it carries is called a closure.

So when makeCountdown returns, its call is over, but seconds can’t be thrown away: the function we got back still holds a link to it. A variable lives as long as some function can still reach it.

Call makeCountdown again and you get a brand-new seconds, and a brand-new function linked to it:

const tick = makeCountdown(3);
const slowTick = makeCountdown(10);

tick();     // 3
tick();     // 2
slowTick(); // 10
tick();     // 1
slowTick(); // 9

Two countdowns, each with its own number, from one piece of code. Nothing outside can touch those numbers except through the functions. That’s how a function keeps a private memory.

Callbacks and higher-order functions

Since a function is a value, a function can take one as an argument. Our countdown prints each number, but printing is only one thing you might want to do with them. So leave that part blank: add a parameter, onTick, and call it with the number inside the loop.

function countdown(from, onTick) {
  for (let seconds = from; seconds > 0; seconds = seconds - 1) {
    onTick(seconds);
  }
}

countdown(3, console.log);
// 3
// 2
// 1

countdown(3, (seconds) => console.log("T minus " + seconds));
// T minus 3
// T minus 2
// T minus 1

The loop is written once, and what it does each round comes from outside.

A function passed in to be called later is a callback. The built-in ones work the same way: setTimeout takes a function and a number of milliseconds, and calls your function when the time is up.

setTimeout(() => console.log("Liftoff"), 1000);

Functions that take or return functions are called higher-order functions. makeCountdown was one: it returned a function.

Recursion

One more thing a function can do with a function: call itself. Here’s the countdown with no loop at all:

function countdown(from) {
  if (from === 0) {
    console.log("Liftoff");
    return;
  }
  console.log(from);
  countdown(from - 1);
}

countdown(3); // 3, 2, 1, Liftoff

countdown(3) prints 3 and calls countdown(2). That prints 2 and calls countdown(1). One calls zero, and zero prints Liftoff and stops.

A function that calls itself is recursive, and every recursive function needs a case where it stops. Delete that first if, and the calls never end.

The call stack

Why does that end badly, instead of running forever like a loop? Because every call has to come back. When countdown(3) calls countdown(2), the first call isn’t finished. It’s waiting, and JavaScript has to remember where to pick up.

Those waiting calls pile up in the call stack. Each call adds a layer, and each return removes one. Without a stopping case, the pile only grows, thousands of calls deep, until JavaScript gives up:

function countdown(from) {
  console.log(from);
  countdown(from - 1);
}

countdown(3); // RangeError: Maximum call stack size exceeded

For counting, a loop is the simpler tool. Recursion earns its place when a problem holds smaller copies of itself: a folder with folders inside it, a menu with menus inside it.

Summary

  • There are three ways to write a function: a declaration, a function expression and an arrow function. Only declarations can be called above the line that defines them.
  • JavaScript doesn’t check how many arguments you send. Missing ones are undefined unless the parameter has a default.
  • A variable lives where it’s declared: global, inside a function, or inside a block for let and const. var ignores blocks.
  • A closure is a function together with the variables it carries. Those variables live as long as the function can reach them.
  • A callback is a function you pass to another function to be called later.
  • A recursive function calls itself and needs a case where it stops, or the call stack overflows.
Video transcript

Intro

Here's a function that makes a countdown you can run one step at a time. Call makeCountdown with three, and it hands back a new function, which we keep in tick. Call tick: three. Again: two. Again: one. Now look at where that number is kept: in a variable called seconds, inside makeCountdown. And makeCountdown finished running before we called tick even once. The function that made the variable is done, and the variable is still here, still counting. How can a variable outlive the function that made it? Today, we find out.

By the end of this video, you'll understand three things. One: the three ways to write a function, and what sets them apart. Two: where a variable lives, and how a function can keep one alive after its maker is done. Three: what happens when a function takes another function, hands one back, or calls itself.

Writing a function

Last time, we wrapped the countdown in a function so we could run it from any number, and we saw that a function is a value, like a number or a string. This time, we go inside. We'll see three ways to write a function, where its variables live, how a function can hold on to them after it's finished, and what a function can do with another function. That last part is how most real JavaScript gets written, so it's where we're headed.

So far we've written every function the same way: the keyword function, a name, and a body. That's a function declaration. There's a second way. Since a function is a value, you can write one without a name and store it in a constant, the way you'd store a number. That's a function expression. Both give you a function called half, and both are called the same way. The difference shows when the call comes before the definition. JavaScript sets up function declarations before it runs the first line, so a call above one works. A constant doesn't exist until its own line runs, so the same call is an error.

The third way arrived in 2015, and it's the one you'll see most. An arrow function drops the keyword. Parameters in parentheses, then an arrow, written as an equals sign followed by a greater-than sign, then the body. When the body is just one expression, drop the braces and the return as well: whatever the expression works out to is what comes back. And with exactly one parameter, the parentheses can go too. Four versions of half, and they all give five. Declarations suit the named functions your program is built from. Arrows suit the small ones you hand to other functions, and we'll be handing a lot of them around before this episode is over.

A parameter is a variable that gets its value from the call. And JavaScript never checks how many values you send. Call countdown with nothing, and from is undefined. There's no error. The loop compares undefined with zero, gets false, and the program prints only Liftoff. Send two values, and the extra one is ignored. Since 2015, a parameter can have a default: an equals sign and a value after its name, used whenever the call leaves that value out. Now countdown with nothing counts from ten.

Scope

Every variable has a scope: the stretch of code where its name means something. A variable declared outside every function is global, and the whole program can see it. A variable declared inside a function is local. Only that function can see it, it's created fresh with every call, and normally it's thrown away when the function returns. Inside can look outside: the function reads planet without trouble. Outside can't look inside: ask for seconds after the call, and JavaScript says it's not defined. Parameters are local too. from exists only during the call.

Since 2015, the curly braces of an if or a loop make a scope as well, for let and const. The seconds in this for loop exists only inside the loop. Which brings us to the var problems we promised last time. var ignores the braces. Declare it inside the loop, and it leaks out: after the loop, seconds is still there, holding zero. And var lets you read a variable above the line that declares it. You get undefined instead of an error, so a mistake in the order of your lines stays quiet. let does the opposite: read it before its line, and JavaScript stops with an error. That's why new code uses let and const, and reads var as the old way.

Closures

Back to the hook. Inside makeCountdown there's a variable, seconds, and a function that uses it. The inner function can see seconds because inside looks outside, the rule from a minute ago. But look at what it does with seconds. It doesn't take a copy of the number. It keeps a link to the variable itself, and every call reads and changes that same variable. Here's the part that matters: a function carries the scope it was created in, wherever it goes. Return it, store it, hand it to someone else, and the link comes along. A function together with the variables it carries is called a closure.

So when makeCountdown returns, its call is over, but seconds can't be thrown away: the function we got back still holds a link to it. That's the answer to the hook. A variable lives as long as some function can still reach it. Call makeCountdown again, with ten this time, and you get a brand-new seconds and a brand-new function linked to it. Two countdowns, each with its own number, from one piece of code. And nothing outside can touch those numbers except through the functions. That's how a function keeps a private memory. Later in this series, it's how a button remembers how many times it's been clicked.

Functions that take functions

Since a function is a value, a function can take one as an argument. Our countdown prints each number, but printing is only one thing you might want to do with them. So leave that part blank. Add a parameter, onTick, and inside the loop, call it with the number. Now the caller fills in the blank with a function. Hand it console dot log, and you get the plain countdown. Hand it an arrow that adds T minus, and you get mission control. The loop is written once, and what it does each round comes from outside. A function passed in to be called later is a callback, and the built-in ones work the same way: setTimeout takes a function and a number of milliseconds, and calls your function when the time is up. Functions that take or return functions are called higher-order functions, and makeCountdown was one.

Recursion

One more thing a function can do with a function: call itself. Here's the countdown with no loop at all. If from is zero, print Liftoff and stop. Otherwise, print the number and call countdown with one less. Three prints three and calls countdown with two. Two prints two and calls one. One calls zero, and zero prints Liftoff. A function that calls itself is recursive, and every recursive function needs a case where it stops. Delete that first if, and the calls never end.

Why does that end badly, instead of running forever like a loop? Because every call has to come back. When countdown three calls countdown two, three isn't finished. It's waiting, and JavaScript has to remember where to pick up. Those waiting calls pile up in the call stack. Each call adds a layer, and each return removes one. Without a stopping case, the pile only grows, thousands of calls deep, until JavaScript gives up with a RangeError: maximum call stack size exceeded. For counting, a loop is the simpler tool. Recursion earns its place when a problem holds smaller copies of itself: a folder with folders inside it, a menu with menus inside it.

Next time

That's JavaScript functions in one line: three ways to write them, variables that live where they're declared, closures that keep them alive, and functions that take functions, make functions, or call themselves. Next time, we stop working one value at a time. Arrays hold lists, objects hold labeled values, and the callbacks from today are how you work through them.

Learn more