topskill.dev
CoursesTracks
0
All courses/Introduction to JavaScriptClosures
Functions
4 / 11
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking○Missing values and deliberate emptiness○Inspect Values in the Console○Inspect the Queue Report○Trace a Faulty Calculation○Repair the Score Calculation✦Module Quiz
○Declaring Variables○let and const in Practice○Operators○Type Conversion○Group and Convert Expense Inputs○Calculate the Event Expense Total○Track a Changing Points Tally○Adjust a Ticket Price✦Module Quiz
○Comparisons and strict equality○Truthiness and combined conditions○Function inputs and results○Conditionals○Combined Conditions Before FizzBuzz○Challenge: FizzBuzz Announcer○Switch Statement○Switch a Venue Sign○Challenge: Power Loadout○For Loops○While Loop○Break and Continue○Stop a Ticket Scan○Challenge: Number Guess Referee○Rainfall Routing Walkthrough○Score Batch Report✦Module Quiz
○Defining Functions○Arrow Functions○Scope●Closures○Project - Calculator○Function Expressions○Ticket Pricing Walkthrough○Shipping Labels with Defaults○Seat Ledger Closure Walkthrough○Private Budget Ledger✦Module Quiz
○Arrays○Student Scoreboard○Challenge: Student Course Scoreboard○Array Mutation Methods○Array Slice and Concat○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every○Charging Rack Restock Report○Pantry Restock Plan✦Module Quiz
○Object Key-Value Pairs○Student Course Record○Object Methods and Destructuring○Object copies and optional properties○Map and Set Collections○Playlist Lookup○Number and BigInt Boundaries○Ticket Ledger○JSON○Throwing and catching errors○Math and Date○Date Basics○Supply Bin Audit○Volunteer Shift Audit○Workshop Attendance Feed○Parcel Scan Feed✦Module Quiz
○String Methods○Template Literals○Regular Expressions○Build a Reminder with Template Literals○Format Pantry Pickup Messages○Validate a Time Slot with Regex○Validate Storage Shelf Labels✦Module Quiz
○Higher-Order Functions○Callbacks○map, filter, and reduce○Student Register with map○Challenge: Student Register○Recursion○Project - Data Transform Pipeline○Extend the inventory report○Handle an Error-First Callback○Report Seat Reservation Results○Summarize Completed Bike Rides○Summarize Delivered Parcels✦Module Quiz
○A notebook object○OOP Introduction○Independent workshop passes○Classes○An inherited notice○Inheritance○A private seat counter○Encapsulation○Equipment desk checkout○Project: Library Checkout✦Module Quiz
○Callback Timing○Asynchronous JavaScript○Promise Rehearsal○Promises and Async Await○Offline API Coordination○Async API Simulation○Partial Results Bulletin○Project: Resilient Awards Feed○Retry a Local Delivery○Project: Reliable Score Delivery✦Module Quiz

Closures

A ticket counter must remember how many tickets it has issued. A function can return another function as its result, just as it can return a string.

In this example, return function () { ... }; creates a function value without a name and gives that value to the caller. The outer function runs once when you create the dispenser. The inner function runs whenever you take a ticket.

javascript
function makeTicketDispenser() {
  let nextTicket = 10;
  return function () {
    const issued = nextTicket;
    nextTicket += 1;
    return issued;
  };
}
const takeTicket = makeTicketDispenser();
console.log(takeTicket(), takeTicket());
const otherDesk = makeTicketDispenser();
console.log(otherDesk());

The returned function keeps access to nextTicket after the outer call finishes. This connection between a function and its surrounding variables is a closure. Each call to the outer function creates separate state. That is why the other desk starts at 10 rather than 12.

Keep your count declaration outside the returned function. Putting it inside would reset it on every call. Your exercise starts each counter at zero and increments before returning, so its first result is 1.

Your Task

  1. Complete makeCounter() so each call creates a private count starting at zero and returns a function that increments and returns that count.
  2. Create a fresh counter and log 1 | 2 | 3 by calling that same counter three times.

Edit script.js, then Run after each step. The supplied probes show the values being checked; leave them in place. Submit checks the numbered tasks in order. You do not need to write extra checkpoint logs.

Hint 1
1 / 2
HINT 1

Return an inner function that updates count each time it runs.

HINT 2

Call the returned function three times and join the results with |.

Files
  • ⋄script.js
Loading editor…
Press Run to execute your code.