Skip to content
Gallery
JS Fundamentals: Objects, Arrays, and Functions
Share
Explore
Functions

icon picker
Closure

Before jumping into closure, let’s review what we know about scope:
How is local and global scope defined?
What is an example of lexical scope?
How do scope chains work?
What is an example of a when you have used a callback?
How would you return data like a string from a function?
How would you return data like another function from a function? What are the differences?

If you are feeling rusty, revisit the section and come back!
The fun part here is that when we went through , we covered everything you need to know about closures. Recall when we discussed lexical scope earlier, a function retains access to variables in the parent scope. A closure is a function that is returned from a function and captures these values.
Let’s take a look!
const clue = () => {
const msg = "Help! I think I found a clue!";
const logger = () => {
console.log(msg);
};

setTimeout(logger, 1000);
console.log("what happens first? this log or the halp above?");
};

clue();

const clueCounter = (msg) => {

let count = 0;
const logger = () => {
console.log(`${msg} ${++count}`);
};

return logger;
};

const funcClueCounter1 = clueCounter('Clue #');


const cC = (msg) => {

let count = 0;
const lg = () => {
console.log(`${msg} ${++count}`);
};

return lg;
};

const cc1 = cC('Clue #');
const cc2 = cC('Another clue #');

cc1(), cc1(), cc1();

cc2();
Let’s take a look at the slides to see this in action:

Next 👉


©2021 for
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.