JavaScript Why return function in a function?

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.

Answers:

Answer

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.

Answer

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>

Answer

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)
}

Answer

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...

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.