DevFox Labs
HomeCoursesRoadmapsChallengesToolsAboutContact

Level 1 · M5 · Lesson 5.5

beginner45 minby DevFox

Scope and closures (basics)

See which boxes a function can reach from where it is written, then write functions that make functions and keep the boxes they use: a rule maker and a task numberer that remembers its count.

  • Fundamentals
  • TypeScript
Scope and closures (basics). Read this lesson at .

Previous lesson · M5 · 5.4Functions as values: callbacks and function types Next lesson · M5 · 5.6void: functions that return nothing

On this page

  • Where a box can be seen
  • Nearest first
  • A function that makes a function
  • A box that lives between calls
  • TaskKit's twin rule comes from a function
  • Predict before you run
  • The common mistake: a box where it is called
  • Exercises
  • Recap
  • A cheat sheet to keep
  • Where to go next
DevFox Labs

Structured lessons and courses for developers who care about craft.

Platform

HomeCoursesRoadmapsAll lessonsChallengesAboutContactRSS feed

Legal

Terms of ServicePrivacy PolicyCookie Policy

© 2026 DevFox Labs. All rights reserved.

    Tested with TypeScript 7.x · Node.js LTS

    In lesson 4.3 you taught TaskKit to refuse a task typed twice. Before add keeps a task, it hands find a rule that compares the tasks on the list, one by one, with the new one:

    index.tsts
          const newTask = capitalize(tidyTask);
          const twin = tasks.find(
            (task) =>
              task.toLowerCase() === newTask.toLowerCase()
          );

    Look at that rule closely. Its only parameter is task, and it makes no box of its own. newTask was made on the line above, outside the arrow. Yet the rule reads it every time find calls it, and it works. Nothing in the course has said why yet.

    Think of the pancake card once more. If it says "use the milk in the blue jug", it only makes sense in your kitchen, where the jug is. Hand the card to a friend, and the jug has to go with it. In this lesson you find out which boxes a function can reach from where it is written, and what happens to them when the function is handed on. By the end you will have a function that makes rules for you, makeRule("call"), and one that numbers your tasks and remembers where it got to.

    Goal of this lesson

    Say which boxes a function can use from where it is written, and write a function that makes and returns another function that keeps the boxes it uses.

    Where a box can be seen

    You already know half of this. A box made inside a block exists only up to that block's closing brace: an if in lesson 3.1, a loop's task in lesson 4.2, a parameter that lives only while its call runs in lesson 5.1. The part of the code where a name means its box is called the box's scope. A box made in the file, outside every function, has the whole file as its scope; a box made inside braces has only those braces.

    The other half is the direction you have used all along without a name: from inside the braces, looking out. Here is a function that works out how much room is left on the list:

    room.tsts
    const limit = 5;
    function roomLeft(tasks: string[]): string {
      const added = tasks.length;
      if (added < limit) {
        const free = limit - added;
        return `Room for ${free} more`;
      }
      return "The list is full";
    }
    console.log(roomLeft(["buy milk", "call mom"]));

    Line 5 makes free out of two boxes it never made. added comes from the function around it, and limit from the file around that. Neither is passed in. When TypeScript meets a name, it looks for its box in the nearest braces around the name first, and only when the box is not there does it look one level further out. Press Next step to follow it looking for limit, or let it play:

    1. The if block: free

      Not here. Only free was made inside these braces.

    2. roomLeft: tasks, added

      Not here. The function made tasks and added.

    3. The file: limit, roomLeft

      Found. limit is 5, made on line 1.

    From line 5, TypeScript looks for limit nearest first
    All 3 steps shown.Step 1 of 3: The if block: freeStep 2 of 3: roomLeft: tasks, addedStep 3 of 3: The file: limit, roomLeft

    All 3 steps shown.

    Run it:

    It prints Room for 3 more. From inside, a function sees every box around it: its own, those of any braces around it, and the file's. From outside it is the other way round, as Module 3 showed: on line 10, added and free are unknown names.

    Nearest first

    The search starts inside and stops at the first box it finds. So a box inside can hide a box outside that has the same name:

    It prints call mom!, then pay rent. Inside shout, the nearest task is its parameter, so the file's task is never looked at. Outside, the parameter does not exist, and task is the file's box again. Neither one changed the other. That is why every function in this course can call its parameter task without trouble: each function's task is its own. That is also why TaskKit's percentFull(added, limit), from lesson 5.1, does not clash with the file's boxes added and limit: inside it, the nearest added and limit are its parameters.

    One more rule: the search starts where the function is written, not where it is called. A function written in the file looks in its own braces, then in the file, wherever the call comes from. A box made inside another function is out of its reach, even when that other function is the one calling it. The common mistake below shows it as an error.

    A function that makes a function

    In lesson 5.4 you wrote isCall and isBuy, two functions that differ in one word, and a third kind of task would mean a third copy. You can write one function that makes them instead: hand it the word, and it hands back the rule.

    Read the first three lines the way lesson 5.4 taught you: makeRule takes a string, and what it gives back has the type (task: string) => boolean, a function that takes a string and gives back a boolean. A function type works as a return type just as it did for a parameter. The body is one line: return hands back an arrow, without calling it. The arrow's task needs no type written, because the return type already says it is a string.

    The arrow uses word, which is not its own: it is the parameter of makeRule. And by the time anyone calls the arrow, makeRule is over. In lesson 5.1, a parameter existed only while its call ran. Press Next step to see what happens to word this time, or Play:

    Step 3 is the one to look at. makeRule has returned, and its box word has not gone with it, because the arrow it handed back still uses it. A function together with the boxes from outside it that it uses is called a closure: the arrow closes over word and carries it wherever it goes, like the jug that goes with the card. Every call of isCall reads that same word, "call". Nothing else can: a line of the file that says word is refused with Cannot find name 'word'., because word was made inside makeRule, out of the file's reach, and only the arrow made there still holds on to it.

    Now press Step on the same program. While the arrow runs, the Call stack column says global › anonymous: your file called the arrow directly, and makeRule is no longer on the stack at all. It is anonymous, not isCall: an arrow takes its box's name only when it is written straight into the box, as left was in lesson 5.2. This one was written after return, with no box, and only reached isCall later.

    A made rule is a function like any other, so it fits wherever the rules of lesson 5.4 did: hand it to countIf, or to filter.

    It prints 2, then [ 'buy milk' ]. This time the parentheses after makeRule are right. In lesson 5.4, isCall() handed over an answer where a function was wanted. Here the answer of makeRule("call") is a function, and that is what countIf gets.

    TaskKit's twin rule is a closure too. The arrow you hand find closes over newTask, the box made on the line above it in the add case. find calls the arrow from inside itself, far from that case, and the arrow still reads the newTask it was written next to.

    A box that lives between calls

    To number tasks, something has to remember the last number. A let count in the file would do it, but then any line in the file could change it by mistake. A closure can keep the box where nothing else reaches it: word above is only read, but a closure can also change the box it keeps, and the change is still there at the next call. Here is a function that makes a numbering function for a list:

    It prints 1. buy milk, 2. call mom and 1. pay rent. makeNumbering takes nothing, so its parentheses are empty, like divider in lesson 5.2, an arrow that takes nothing. It makes a box count and hands back an arrow with a body in braces that adds 1 to count and gives back the numbered task. label goes from 1 to 2 because count is not a fresh box at each call: it is the box the arrow kept.

    Then why does other start at 1 again? Each call of makeNumbering runs its body again, and let count = 0; makes a new box each time. Two calls, two closures, two boxes:

    label: made first, called twice

    • Does: Counts on from its own box: its next task gets 3
    • Never: It never sees the count of other

    other: made second, called once

    • Does: Starts from a new box: its first task gets 1
    • Never: It never goes on from where label got to
    Each call of makeNumbering made a function with its own count

    Nothing outside can reach count either. It is a box of makeNumbering, so the file cannot see it, and the only way to change it is to call the arrow.

    TaskKit's twin rule comes from a function

    Now TaskKit's step for this lesson. A function can make the twin rule, the way makeRule makes its rules, and the call then says what it looks for.

    Open index.ts in ~/projects/taskkit. At the top of the file, under alphabetical, declare the function that makes the rule:

    Then, in the add case, write the check with it:

    sameTask(newTask) runs first and hands back an arrow that keeps sameTask's own newTask, a parameter holding the same text as the add case's box of that name: two boxes in two scopes. find then calls that arrow on the tasks one by one, and stops at the first one it says true to. Check the file with tsc (the TypeScript compiler, which npx starts) and run it with a task typed twice:

    npx tsc prints nothing: the file passes. Then TaskKit prints:

    The second one is still refused, by a rule that now comes from a function with a name, sameTask.

    Predict before you run

    Two numberings, called in turn. Follow each one's own count.

    Predict

    What is the last line this program prints?

    The common mistake: a box where it is called

    A function that is called from inside another one looks as if it were inside it. So it is easy to expect it to see that function's boxes.

    Common mistake

    Reading a box made in the function that calls it

    report makes limit and calls isFull, so limit seems to be right there when isFull runs:

    npx tsc --noEmit --types node report.ts refuses it:

    The first line is one line in your terminal, broken here to fit the page. TS2304 is the number of this message: TS for TypeScript.

    Cannot find name 'limit'.

    The fix

    Make limit in the file, the place where both functions are written, so both can see it:

    It prints The list is full.

    isFull is written in the file, so it looks in its own braces and then in the file. The limit inside report is in neither: it exists only inside report's braces, wherever isFull is called from. So when Cannot find name names a box you can see in the file, look at where the function is written, not where it is called. Move the box out to where both functions can see it, or pass it in as a parameter.

    Practice

    1. 1
    2. 2
    3. 3
    4. 4

    Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.

    Exercises

    Each one runs in your browser. Press Check when you think you have it; if you are stuck, the hints come one at a time.

    Recap

    Recap · 3 questions

    Check yourself

    Inside a function, where is a name looked for first?

    Check yourself

    Called from report, can isFull see report's boxes?

    Check yourself

    makeRule("call") has returned. What happens to its box word?

    0 of 0 answered.

    A cheat sheet to keep

    Cheat sheet

    Scope and closures (basics)

    What things are

    WordWhat it means
    ScopeThe part of the code where a name means its box
    Looking outOwn braces first, then outward to the file
    A hidden nameA box inside with the same name wins inside
    ClosureA function with the outside boxes it uses

    Code

    WriteTo
    ): (task: string) => boolean {Promise to give back a function
    return (task) => task.startsWith(word);Return an arrow using word
    const isCall = makeRule("call");Make a rule and keep it in a box
    countIf(today, makeRule("call"))Make a rule and hand it straight over
    let count = 0; before returnA box the arrow keeps between calls

    Rules

    RuleWhat it means
    Inside sees outA function reads the boxes around it
    Outside sees nothing inA box in braces ends at their }
    Written, not calledWhere it is written decides what it reaches
    A kept box lives onAfter the call that made it is over
    One box per callEach makeNumbering() makes a new count
    Out of reachTS2304: Cannot find name
    No return type on makeRuleThe arrow's task is any:

    Where to go next

    You can now say which boxes a function can use: its own, then those around it, out to the file, all decided by where it is written. You can write a function that makes and hands back another function, and you know that the boxes it uses go with it, read or changed, for as long as the function lives.

    Next is void: functions that return nothing. Every function in this lesson gave something back. There you write functions whose whole job is to do something, such as print a line, and see what TypeScript says they return.

    Before you move on, run node index.ts add "buy milk" "BUY MILK" "Buy Milk". Predict before you press Enter how many tasks are added and which lines say Already on the list.

    TS7006
    Keep it outside the arrowA box made inside is new at every call
    Exercise · Read the code

    Two boxes called added

    What does this program print?

    ts
    const added = 3;
    const limit = 5;
    function percentFull(added: number, limit: number): number {
      return Math.round((added / limit) * 100);
    }
    console.log(percentFull(1, 4));
    console.log(added);

    Outputtext
    ============================
    TaskKit 0.1
    Your tasks, in your terminal
    ============================
    Added: Buy milk
    Already on the list: Buy milk
    Tasks added: 1 of 5, room for 4 more
    List 20% full
    Your list, A to Z:
    1. Buy milk
    Outputtext
    report.ts:2:19 - error TS2304: Cannot find
    name 'limit'.
    
    2   return added >= limit;
                        ~~~~~
    
    
    Found 1 error in report.ts:2
    room.tsts
    const limit = 5;
    function roomLeft(tasks: string[]): string {
      const added = tasks.length;
      if (added < limit) {
        const free = limit - added;
        return `Room for ${free} more`;
      }
      return "The list is full";
    }
    console.log(roomLeft(["buy milk", "call mom"]));
    shout.tsts
    const task = "pay rent";
    function shout(task: string): string {
      return `${task}!`;
    }
    console.log(shout("call mom"));
    console.log(task);
    ts
    function makeRule(
      word: string
    ): (task: string) => boolean {
      return (task) => task.startsWith(word);
    }
    rule.tsts
    function makeRule(
      word: string
    ): (task: string) => boolean {
      return (task) => task.startsWith(word);
    }
    const isCall = makeRule("call");
    console.log(isCall("call mom"));
    console.log(isCall("buy milk"));
    count.tsts
    function makeRule(
      word: string
    ): (task: string) => boolean {
      return (task) => task.startsWith(word);
    }
    function countIf(
      tasks: string[],
      rule: (task: string) => boolean
    ): number {
      let count = 0;
      for (const task of tasks) {
        if (rule(task)) {
          count += 1;
        }
      }
      return count;
    }
    const today = ["call mom", "buy milk", "call the bank"];
    console.log(countIf(today, makeRule("call")));
    console.log(today.filter(makeRule("buy")));
    numbering.tsts
    function makeNumbering(): (task: string) => string {
      let count = 0;
      return (task) => {
        count += 1;
        return `${count}. ${task}`;
      };
    }
    const label = makeNumbering();
    console.log(label("buy milk"));
    console.log(label("call mom"));
    const other = makeNumbering();
    console.log(other("pay rent"));
    const label = makeNumbering();
    console.log(label("buy milk"));
    console.log(label("call mom"));

    Its own count: 2

    const other = makeNumbering();
    console.log(other("pay rent"));

    Its own count: 1

    index.tsts
    function alphabetical(a: string, b: string): number {
      return a.localeCompare(b);
    }
    function sameTask(newTask: string): (task: string) => boolean {
      return (task) =>
        task.toLowerCase() === newTask.toLowerCase();
    }
    index.tsts
          const newTask = capitalize(tidyTask);
          const twin = tasks.find(
            (task) =>
              task.toLowerCase() === newTask.toLowerCase()
          );
          const twin = tasks.find(sameTask(newTask));
    bash
    npx tsc --noEmit --types node index.ts
    node index.ts add "buy milk" "Buy milk"
    ts
    function makeNumbering(): (task: string) => string {
      let count = 0;
      return (task) => {
        count += 1;
        return `${count}. ${task}`;
      };
    }
    const shopping = makeNumbering();
    const calls = makeNumbering();
    console.log(shopping("buy milk"));
    console.log(calls("call mom"));
    console.log(shopping("buy bread"));
    report.tsts
    function isFull(added: number): boolean {
      return added >= limit;
    }
    function report(added: number): string {
      const limit = 5;
      if (isFull(added)) {
        return "The list is full";
      }
      return `Room for ${limit - added} more`;
    }
    console.log(report(5));
    report.tsts
    const limit = 5;
    function isFull(added: number): boolean {
      return added >= limit;
    }
    function report(added: number): string {
      if (isFull(added)) {
        return "The list is full";
      }
      return `Room for ${limit - added} more`;
    }
    console.log(report(5));
    CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
    ts
    function makeRule(
      word: string
    ): (task: string) => boolean {
      return (task) => task.startsWith(word);
    }
    const isCall = makeRule("call");
    console.log(isCall("call mom"));
    console.log(isCall("buy milk"));
    MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
    • word"call""call"
    • isCall(task) => …(task) => …
    • task"call mom""call mom"
    OutputEverything the program has printed so far.
    Nothing printed yetNothing printed yet

    Line 6 calls makeRule with "call". The computer leaves the line half done and goes into the function.

    A fresh box word holds "call". return hands back an arrow, without running it.

    makeRule is over, but word is still there: the arrow uses it. The arrow is now in the box isCall. The Memory column shows every box the program has, so word stands beside isCall, yet it is not the file's box: only the arrow can reach it.

    Line 7 calls the arrow, with a fresh task. It reads word, the box it kept: "call mom" starts with "call".

    The arrow gave back true, and line 7 prints it.

    Line 8 calls the arrow again. word is still "call", and "buy milk" does not start with it.

    The arrow gave back false, and line 8 prints it.

    Step 1 of 7, line 6

    No boxes yet. Running in global.

    Every step as text
    1. Line 6.

      Line 6 calls makeRule with "call". The computer leaves the line half done and goes into the function.

    2. Line 4. word = "call". Inside makeRule.

      A fresh box word holds "call". return hands back an arrow, without running it.

    3. Line 6. word = "call", isCall = (task) => ….

      makeRule is over, but word is still there: the arrow uses it. The arrow is now in the box isCall. The Memory column shows every box the program has, so word stands beside isCall, yet it is not the file's box: only the arrow can reach it.

    4. Line 4. word = "call", isCall = (task) => …, task = "call mom". Inside anonymous.

      Line 7 calls the arrow, with a fresh task. It reads word, the box it kept: "call mom" starts with "call".

    5. Line 7. word = "call", isCall = (task) => ….

      The arrow gave back true, and line 7 prints it.

      Prints true
    6. Line 4. word = "call", isCall = (task) => …, task = "buy milk". Inside anonymous.

      Line 8 calls the arrow again. word is still "call", and "buy milk" does not start with it.

    7. Line 8. word = "call", isCall = (task) => ….

      The arrow gave back false, and line 8 prints it.

      Prints false
    makeRule is over, and the arrow it made still reads word
    Exercise · Fix the error

    Say what makeRule gives back

    TypeScript refuses this program with Parameter 'task' implicitly has an 'any' type. Write the return type of makeRule, and change nothing else, so that the program prints true.

    Loading the editor…

    Exercise · Fix the error

    Keep the count between calls

    This program prints 1. buy milk and then 1. call mom. Fix it so that it prints 1. buy milk and then 2. call mom.

    Loading the editor…

    Exercise · Write the code

    Write shorterThan

    Write a function shorterThan that takes a number, limit, and gives back a rule: a function that takes a task and gives back true when the task has fewer than limit characters. Write the types of the parameter and of what it gives back. The lines that use it are already there; they print [ 'buy milk', 'pay rent' ] and then [].

    Loading the editor…