What value does this Javascript factory function add?

I stumbled upon this block of code and really don't see the need to return a function when an external function takes no arguments?

var percent = (function() {
    var fmt = d3.format(".2f");
    return function(n) { return fmt(n) + "%"; };
})()

Something is missing for me or it can be rewritten as:

var percent = function(n) {
    return d3.format(".2f")(n) + "%";
}
+5
source share
1 answer

He can, but then you call d3.format(".2f")every time, not once. Depending on what the function does and how often it is called, this may add extra overhead.

With the IIEF (immediately called function expression) returning a closure, you "cache" fmtfor all future uses percent.

+5
source

All Articles