I was going through the closures definition in Mozilla and found this example -
function makeSizer(size) {
return function () {
document.body.style.fontSize = `${size}px`;
};
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
What I still don't understand is that if I want to increase the font, I can still do it this way -
function makeSizer(size) {
document.body.style.fontSize = `${size}px`;
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
What is the concept of closures doing here? Why the extra inner function? Please correct my understanding.
The function closures the
sizevariable, so when you call the returned function the value ofsizewill be the same as you gave it to themakeSizerfunction. Without closuring,makeSizerreturns undefined and cannot be reused.