0

See this example:

var tools1 = require('../tools/tools1');
var test_func = function(arg1, arg2, arg3) {

    var local_var_1 = "lc1";
    var local_var_2 = "lc2";

    return function(data) {
    var result = tools1.doSth(local_var_1);
        result = result+local_var_2;
    }
}

exports.test_func = test_func;

I do not understand what does inner function do what it is for!

2 Answers 2

2

In javascript when you return function it returns reference of that function and you can call it later.

In your Code when you do var result = test_func(), result will hold reference of that function. Then later you can call that returned function like result(data).


A basic example:

function sum(x, y) {
  var rs = x+y;
  return function(message) {
    console.log(message + rs); //rs holds its value because of clousers
  }
}

var result = sum(2, 3);
result("This is result: ");

Variables that are used locally, but defined in an enclosing scope like rs in above example because of Closures

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I think I got it. You mean instead of getting an object or string or ... from a function as its output, we can get a function as output. right!?
Yes you can return a function. As i already mentioned we are actually returning Reference.
2

This concept of function inside a function is known as closure in JavaScript. They are self invoking and makes it possible to have a function's private variables. I am representing a similiar code of yours which I found in W3schools.com.

var add = (function () { 
    var counter = 0;
    return function () {return counter += 1;}
})();

add();

add();

add();

Initially, the counter is set to 0 and then it returns a function reference. The counter is protected by the scope of the anonymous function, and can only be changed using the add() function. The counter is set to 3 then, as add() function is called three times.

In the very similiar way, your code is working I guess:

var test_func = function(arg1, arg2, arg3) {

    var local_var_1 = "lc1";
    var local_var_2 = "lc2";

    return function(data) {
    var result = tools1.doSth(local_var_1);
        result = result+local_var_2;
    }
}

the local_var_1 and local_var_2 is set to "lc1' and "lc2" and returning a function reference. The inner function then comes and do some operation with tools1.doSth() on local_var_1 and append the result with local_var_2.

Note: I am not clear with the output of your code, so I tried to tell you the steps with help of another code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.