, 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!
constclue = () => {
constmsg = "Help! I think I found a clue!";
constlogger = () => {
console.log(msg);
};
setTimeout(logger, 1000);
console.log("what happens first? this log or the halp above?");
};
clue();
constclueCounter = (msg) => {
let count = 0;
constlogger = () => {
console.log(`${msg} ${++count}`);
};
return logger;
};
const funcClueCounter1 = clueCounter('Clue #');
const cC = (msg) => {
let count = 0;
constlg = () => {
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: