10
var favoriteColor = "blue";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);

Why getColor is not blue. getColor() is blue. getColor also becomes a function? Because we return a function in colorGenerator?

I am confused about these. Thank you for your help.

codemonkey
  • 331
  • 1
  • 4
  • 16
  • 4
    `colorGenerator` is returning a **function**. To get the color name, you need to call that function. `getColor()` – Tushar Feb 03 '16 at 03:26
  • Here is a blog that gives the philosophy behind function returning functions: https://davidwalsh.name/javascript-functions – karthikr Feb 03 '16 at 03:28
  • possible duplicate of [What's the purpose of returning a function from a function?](http://stackoverflow.com/q/31953717/1048572) and maybe [Javascript curry - what are the practical applications?](http://stackoverflow.com/q/113780/1048572) – Bergi Feb 03 '16 at 04:24

6 Answers6

6

Javascript has first-class functions, meaning that functions can be passed around like any other argument or variable, you can even return functions - as per your example.

when you call getColor, you'll get back a function because that's what it is (colorGenerator returns a function).

When you call getColor() you're executing that function, and getting the string return value "blue";

Delving a little deeper, in your specific case, colorGenerator is in fact an identity generator. In functional programming, an identity is simply a function that returns it's original input. It is useful in functional-style programming, namely composition.

Whether you are trying to use a functional style or not isn't clear, so I'll stop by strongly recommending this free online book Mostly adequate guide to functional programming It is very easy to digest and covers the matter from newcomer to pro. If you want to go further, I'd follow-through with Javascript Allongé, another great free JavaScript book which covers functional programming.

Sebastien Daniel
  • 4,649
  • 3
  • 19
  • 34
5

JavaScript Why return function in a function?

One possible purpose of returning a function in a function could be to create a queue of function references that could be called in order, or by index

var favoriteColors = ["blue", "red", "green", "orange", "brown"],
  queue = [];

function colorGenerator(color) {
  return function() {
    return color;
  };
}
favoriteColors.forEach(function(favoriteColor, key) {
  var getColor = colorGenerator(favoriteColor);
  queue[key] = getColor
});

for (var i = 0; i < queue.length; i++) {
  var div = document.createElement("div");
  div.textContent = i;
  // call function at index `i` of `queue` array
  div.style.color = queue[i](); 
  document.body.appendChild(div)
}
guest271314
  • 1
  • 15
  • 104
  • 177
2

Let's dissect this:

var favoriteColor = "blue";
function colorGenerator(color) {
    return function () { return color; };
}

This method returns a function that, in turn, returns a value (color). So doing this:

var getColor = colorGenerator(favoriteColor);

means that getColor is function() {return "blue";}. Therefore, doing:

getColor();

after setting is value with return "blue".


Test:

var favoriteColor = "blue";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);

document.getElementsByClassName("foo")[0].innerHTML = "colorGenerator returns: " + colorGenerator(favoriteColor);
document.getElementsByClassName("bar")[0].innerHTML = "getColor returns: " + getColor();
<div class="foo"></div>
<div class="bar"></div>
AMACB
  • 1,290
  • 2
  • 18
  • 26
2

It's called making a closure. Basically for each call of that colorGenerator function the vars local to it will stay around and be represented in the call of the function it returns.

See this:

function colorGenerator(color) {
    return function () { return color; };
}

// remember these are functions to be called, not the actual color names
var getRed = colorGenerator('red');
var getBlue = colorGenerator('blue');

// now each time we call the returned function of
// each, it will say the color we want
alert( getRed() + " and " + getBlue() ); // -> "red and blue"

I don't know the context of this snippet of code, so why you'd basically need a factory for making functions that return a certain color name, I don't know. But that's essentially what it'll do.

For explaining why that would be useful in a certain context we'd probably have to know the context...

Jimbo Jonny
  • 3,549
  • 1
  • 19
  • 23
1

Hopefully this example can help you to understand how to use the return function

The following example illustrates the use of the return statement to return a function.

JavaScript

function doWork() {
    return function calculate(y) { return y + 1; };
}

var func = doWork();
var x = func(5);
document.write(x);

// Output: 6

PS:
return[(][expression][)];

The optional expression argument is the value to be returned from the function.If omitted, the function does not return a value.
You use the return statement to stop execution of a function and return the value of expression.If expression is omitted, or no return statement is executed from within the function, the expression that called the current function is assigned the value undefined.

Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
  • Hi @Weiting I've put more detail content for you – Willie Cheng Feb 03 '16 at 05:21
  • 1
    @Weiting - Technically no, because that `y` is a parameter in the returned function. It's the calling OF that returned function that would need to have an argument supplied. **HOWEVER**, the point of confusion here is that if there isn't any supplied arguments or other local vars in the function returning the function (i.e. no local data being made persistent by the closure) then what exactly could be the point of making that closure? Making a pointless example of a closure on a question that's basically asking about what the point of a closure is...that's not quite helpful... – Jimbo Jonny Feb 03 '16 at 13:24
0

most time we return funciton, our target is limit variable scope and keep state. so your code should be:

function colorGenerator(color) {
    var favoriteColor = color; //here keep state
  return function (c) { return c===favoriteColor; };
}
var isorange = colorGenerator("orange"); //because you only call colorGenerator one time, so function isorange keep the state : 'orange'
isorange('black') //here return false
isorange('orange') //here return true
defend orca
  • 617
  • 7
  • 17