• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops○While Loop○Break and Continue
○Defining Functions○Arrow Functions○Scope●Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○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
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods○Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes○Inheritance○Encapsulation
○Asynchronous JavaScript○Promises and Async Await○Async API Simulation

Closures

A closure lets an inner function remember the variables around it. A counter is the clearest beginner example because each call proves the function kept its previous state.

Example

javascript
function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

Your Task

  1. Write makeCounter() so it returns a function that increases and returns a private count value.
  2. Display 1 | 2 | 3 in #output by calling the same counter three times.
Hint 1
1 / 2
HINT 1

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

Loading editor…
READY
intercourses
javascript