0

If i need to write a java script function that takes an argument and returns a function that returns that argument, i can think of following two implementations. Are both of these same ? or there is anything different technically ? Both works and returns the same result.

/*Implemenation 1*/
function myWieredFunc(arg){
    var retf=function inner(){
        return arg;
    };
    return retf;
}

/* Implemenation 2 */
function myWieredFunc(arg){
    return function(){
        return arg;
    };
}

To use these:

 var f = myWieredFunc(84);       
 alert(f());
2
  • 2
    It does the same thing. You don't need the variable. Commented Feb 8, 2014 at 23:38
  • And even in the first example, you don't need to name the inner function ("inner") at all Commented Feb 8, 2014 at 23:48

3 Answers 3

1

This would be the way to write it

function wrap(arg) {
    return function() {
        return arg;
    };
};

If you wanted to make it more flexible you could allow multiple arguments:

function wrap() {
    var args = arguments;
    return function() {
        return args;
    };
};

var later = wrap('hello', 'world');
var result = later();
console.log(result); // ["hello", "world"]
Sign up to request clarification or add additional context in comments.

Comments

0

There is no reason for the variable in the code shown - functions are objects are values. As you've shown this means that function-objects can be assigned to a variable which is later evaluated and returned, or returned directly from the Function Expression.

As such, both forms are generally held equivalent and the closure over arg is unaffected.

However, in the first form..

  1. Function.toString and stack-traces will normally include the function name, this makes "named functions", as in the first example sometimes more useful in debugging. Additionally, Firefox will expose function names - e.g. "inner" - through the non-standard Function.name property. (The function name can be specified without the use of the retf variable.)

  2. Two additional bindings are introduced - retf in the outer function and inner in the inner function. These variables could be observed in the the applicable scope when stopping via a break-point - but are not otherwise accessible in the code shown.

Comments

0

They are the same thing, the second is using an "Anonymous" function which just means its a function that is not given a name or assigned to a variable.

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.