Why would a closure be useful in this instance? (JavaScript)?

MDN offers the following as a practical use for a closure:

function makeSizer(size) {

  return function() {

    document.body.style.fontSize = size + 'px';

  };

}

var size12 = makeSizer(12);

var size14 = makeSizer(14);

var size16 = makeSizer(16);

How is this more beneficial than just using:

function makeSizer(size) {

  return document.body.style.fontSize = size + 'px';

}

2 Answers

Relevance
  • 1 month ago
    Favorite Answer

    What that closure will do is give you something that can be called later, without arguments, to do the size setting specified in the size argument. 

    The non-closure version of that isn't what you typed, though.  The alternative would be more like:

    function setBodySize(size) {

        document.body.style.fontSize = size + 'px';

    }

    ...and then define functions that call that, as in:

    function size12() { setBodySize(12); }

    function size14() { setBodySize(14); }

    function size16() { setBodySize(16); }

    I suppose that the reason for either one of those is that you need to pass a no-argument function to some other function that will perform the setting when it's called by that other function.  Both versions get that done.  The closure version takes a bit less typing, I think, but more overhead at run-time. 

    • Commenter avatarLogin to reply the answers
  • Anonymous
    1 month ago

    You can also make them together (with uptodate JavaScript)

    const [size12, size14, size16] = [12,14,16].map(makeSizer)

    Now you have three handy functions that don't have any parameters. 

    size12();

    // for IE9 where no arguments are allowed on setInterval

    setInterval(size14, 100); 

    • husoski
      Lv 7
      1 month agoReport

       You had my up-thumb before, but I'd give you another one for the update I just saw.  Is that .map() method new in ES6?

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.