1252748
1252748

Reputation: 15372

Why would a function be returned in this example instead of just a string

In an answer to this question, I can see the value of i being retained by sort of throwing it into another function:

var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

http://jsbin.com/raxifitaberu/1/edit

Why does the function createfunc() need to return another function? Why is that any better than just returning the string:

 var myArray = [];

 function createFunc(i){
    return "My value: " + i; 
};

 for (var i = 0; i < 5; i++){
     myArray[i]=createFunc(i);        
 }

 console.log(myArray[0]);
 console.log(myArray[1]);
 console.log(myArray[2]);

http://jsbin.com/demiloronohe/1/edit

Is there some advantage to putting function behind the return?

Upvotes: 2

Views: 53

Answers (2)

Mritunjay
Mritunjay

Reputation: 25882

As @sirko mentioned in his comments in a case like bellow it won't work.

 var myArray = [];

 function createFunc(i){
    return function(b){
        return i + b;
    }
};

 for (var i = 0; i < 5; i++){
     myArray[i] = createFunc(i);
 }

 for (var j = 0; j < 5; j++){
     console.log(myArray[j](j));
 }

So here you need to return the answer according to the parameter given to the inner function. That is the case @sirko wanted to point out, correct me if I am wrong.

Upvotes: 0

Bergi
Bergi

Reputation: 664405

In your example it's indeed not necessary, as the function returns a constant expression (Ignoring the side effect of executing console.log and taking that as a "return" value)

However, we could give it a parameter and involve some logic:

var funcs = [];

function createfunc(i) {
    return function(j) {
        if (i == j) console.log("You've found " + i);
        else console.log("I'm not " + j);
    };
}

for (var i = 0; i < 3; i++)
    funcs[i] = createfunc(i);
for (var j = 0; j < 3; j++)
    funcs[j](2);

I hope it is getting more clear now. Of course, you can always avoid closures by capturing their state in an explicit data object (the strings in your example) and passing these then to plain functions as an extra argument (the console.log that you moved into the loop) when you otherwise would just have executed the closure.

Upvotes: 1

Related Questions