Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What value does this Javascript function factory add?

I stumbled upon this block of code and don't really see the need for returning a function when the outer function doesn't take any arguments?

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

Am I missing something or can it be rewritten as:

var percent = function(n) {
    return d3.format(".2f")(n) + "%";
}
like image 239
dani Avatar asked Mar 01 '13 12:03

dani


People also ask

What is the factory function in JavaScript?

A factory function can be defined as a function that creates an object and returns it. It is similar to constructor functions/class functions. The factory function is a very useful tool in JavaScript since it returns the object of any class directly.

What is factory function in JavaScript w3schools?

Introduction to the factory functions in JavaScriptWhen a function creates and returns a new object, it is called a factory function. The createPerson() is a factory function because it returns a new person object. By using the factory function, you create any number of the person objects without duplicating code.

When would you use a factory function?

Factory functions are functions that return objects. We can use factory functions and closures to have private variables and private functions, only exposing what we want to our consumer through the object we return, all while avoiding the this keyword. Factories make for easy composition of values and functionality.

Which of the following is a factory function?

3. Which of the following is a factory function? Explanation: jQuery() is a factory function rather than a constructor: it returns a newly created object but is not used with the new keyword. jQuery objects define many methods for operating on the sets of elements they represent.


1 Answers

It can, but then you are calling d3.format(".2f") each time instead of once only. Depending on what the function is doing and how often it is called, this could add an additional performance overhead.

With the IIEF (immediately invoked function expression) returning the closure, you are "caching" fmt for all future uses of percent.

like image 175
Felix Kling Avatar answered Sep 18 '22 23:09

Felix Kling