Check out a free preview of the full A Practical Guide to Algorithms with JavaScript course

The "Memoization with Closure Exercise" Lesson is part of the full, A Practical Guide to Algorithms with JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

In this exercise, students improve the memoize function by moving the cache into a closure.

Preview
Close

Transcript from the "Memoization with Closure Exercise" Lesson

[00:00:00]
>> Bianca Gandolfo: So we're gonna keep going with this so the next exercise.
>> Bianca Gandolfo: And you probably saw the sneak preview. There's the solutions, which I don't recommend looking at all the solutions and copying them. It's not a way to learn. But they are available for you especially for those of you who aren't here in person to have as a reference.

[00:00:27]
But if you haven't finished the first two you can just copy the solution from the task two and use it for task three. Because we're gonna clean up our approach and make this better.
>> Bianca Gandolfo: Okay, so.
>> Bianca Gandolfo: All right, so task three is all about cleaning up our global scope.

[00:00:59]
This task is for our advanced viewers, if you are not familiar with closures I recommend just sticking with Exercise 1. If you have played with closures a bit or you wanna take it for a whirl, this is the classic example of when and how to use a closure.

[00:01:17]
And we'll go over it in ten minutes after this. But so the pro tip here, use a closure to return a function that you can call later.
>> Bianca Gandolfo: So you can see that we're invoking this function and saving it into a variable name. Then with that variable name we're calling it again.

[00:01:45]
>> Bianca Gandolfo: That's a key.
>> Bianca Gandolfo: Aspect of this being a closure. If it was only returning a primitive value and not a function then you wouldn't be able to call it again. It would just be saved to some value. So it's important that we're returning function so that we can call it later.

[00:02:03]
And inside of our closure we retain access to variables that were passed in before, which is a key. So in a closure you can remember prior values. And if you haven't worked with closures yet that probably sounds like Greek and that's okay. Stick with Exercise 1, we'll go through the solution and you'll learn about how closures work.

[00:02:25]
So don't stress about it if that sounds too complicated.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now