Welcome to Day 15 of our JavaScript workshop! Today, we will dive into closures, an essential concept for creating powerful and encapsulated code. Let's get started!
- Task 1: Write a function that returns another function, where the inner function accesses a variable from the outer function's scope. Call the inner function and log the result.
- Task 2: Create a closure that maintains a private counter. Implement functions to increment and get the current value of the counter.
- Task 3: Write a function that generates unique IDs. Use a closure to keep track of the last generated ID and increment it with each call.
- Task 4: Create a closure that captures a user's name and returns a function that greets the user by name.
- Task 5: Write a loop that creates an array of functions. Each function should log its index when called. Use a closure to ensure each function logs the correct index.
- Task 6: Use closures to create a simple module for managing a collection of items. Implement methods to add, remove, and list items.
- Task 7: Write a function that memoizes the results of another function. Use a closure to store the results of previous computations.
- Task 8: Create a memoized version of a function that calculates the factorial of a number.
- Basic Closure Script: Write a script that demonstrates a basic closure with a function returning another function that accesses the outer function's variable.
- Counter Closure Script: Create a script that uses a closure to maintain a private counter with increment and get functions.
- Unique ID Generator Script: Write a script that generates unique IDs using a closure to keep track of the last generated ID.
- Loop Closure Script: Create a script that demonstrates closures in loops to ensure functions log the correct index.
- Memoization Script: Write a script that memoizes the results of a function and demonstrates it with a factorial calculation.
By the end of these activities, students will:
- ✅ Understand and create closures in JavaScript.
- ✅ Use closures to maintain private state and create encapsulated modules.
- ✅ Apply closures in practical scenarios like generating unique IDs and memoization.
- ✅ Use closures in loops to capture and use variables correctly.
Happy Coding🚀