Javascript closure returning string instead of function

Related searches

I am trying to write a simple compose function that takes a series of functions, and composes them like so:

compose(func1, func2, func3)(n) === func1(func2(func3(n)))

I do so by recursing through a rest parameter,

var compose = function(...args) {
    return (n) => {
        if (args.length) {
            return args[0](compose(args.slice(1)));
        } else {
            return n;
        }
    };
};

I then attempt to compose a new function made up of a series of other functions,

var plusOneAndTwo = compose((n) => n + 1, (n) => n + 2);
plusOneAndTwo(1);

Instead of returning 4, I get back the body of the inner, anonymous function inside of compose as a string,

"(n) => {
        if (args.length) {
            return args[0](compose(args.slice(1)));
        } else {
            return n;
        }
    }1"

Note the "1" at the end of the string! I have no idea why this is happening, and in particular I'm perplexed by how a 1 is getting appended to the end of that.

Any clarification is appreciated, thanks!

The problem occurs in the recursive call to compose. In particular, you are not passing the parameter n to it (as also suggested by others above). Furthermore, you need to expand the rest parameter in the call.

You should use something like:

return args[0](compose(...args.slice(1))(n))

In your case, you are simply returning:

return args[0](compose(args.slice(1)));

In your example you call compose((n) => n + 1, (n) => n + 2);. Compose then returns a function taking n as a parameter. In this function, args.length becomes 1 (i.e. true-is), args[0] becomes (n) => n + 1 and args.slice(1) becomes [(n) => n + 2].

Next, you call this returned function with the parameter n = 1. As args.length is 1, the if() statement will go into the if() case. In this if case, it will call args[0] with the argument compose(args.slice(1)).

In this recursive call, compose(args.slice(1)) is evaluated to a function, taking n as a parameter and the same function body. This function is then given as the parameter n to args[0] (in the outer call). Recall that args[0] in this scenario is the function (n) => n + 1.

Thus the call as a whole is equivalent to:

// returned from the recursive call to compose(args.slice(1))
var n = (n) => {
        if (args.length) {
            return args[0](compose(args.slice(1)));
        } else {
            return n;
        }
}
// applied to arg[0] == (n) => n + 1
return n + 1

This means that the code will attempt to add a function with the number 1. In JavaScript adding a function and a number results in both objects coerced into a string. Casting a number into a string is trivial, casting a function into a string returns the function source code. These strings are then added to give the return value you saw: The function body as a string with the 1 at the end.

Closures, In JavaScript, closures are created every time a function is created, The function it returns takes a single argument y , and returns the sum of x and y . Instead, you can access them using the three public functions that are returned in which help refers to the corresponding string from the helpText array. A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

You just have to call the composed function:

 return args[0](compose(...args.slice(1))(n));

Or without recursion it'll be:

 const compose = (...fns) => start => fns.reduceRight((acc, fn) => fn(acc), start);

Variable scope, closure, Nested functions are quite common in JavaScript. What's much more interesting, a nested function can be returned: either as a� The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression. This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope. This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

You could take a different approach by returning a new function or returning the last function for calling with arguments.

const
    compose = (...fns) => fns.length
        ? v => compose(...fns.slice(0, -1))(fns.pop()(v))
        : v => v,
    fn1 = n => n * 5,
    fn2 = n => n + 2,
    fn3 = n => n * 7;

console.log(fn1(fn2(fn3(1))));
console.log(compose(fn1, fn2, fn3)(1));

Functions :: Eloquent JavaScript, A return statement determines the value the function returns. Instead of the function keyword, it uses an arrow ( => ) made up of an equal a specific instance of a local binding in an enclosing scope—is called closure. It takes two arguments: the current number and a string that records how we reached this number. The major difference from other ways we’ve seen is that the function is created literally from a string, that is passed at run time. All previous declarations required us, programmers, to write the function code in the script. But new Function allows to turn any string into a function. For example, we can receive a new function from a server

Closures in Javascript for beginners, Closures are one of the key concepts of JavaScript and allow developers to write better code. The function buildName() declares a local variable greeting and returns it. The name of every property is a string, and any piece of a program can get Often, JS programmers resort to coding conventions rather than absolute� When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller":

The Beginner's Guide to JavaScript Closure and Its Usages, Now, instead of executing the sayHi() function inside the greeting() function, the greeting() function returns the sayHi() function object. Note that functions are the � In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables

Since you are just returning speak_and_change_x, rather than invoking it using (), nothing will be alerted when you write cat().However, writing cat()() will alert (“meow”) because it is equivalent to invoking the function cat returns - and that is the same as speak_and_change_x().

Comments
  • compose returns a function, yes. You're passing the return value of compose, which is a function, to args[0](). I don't think it's a good idea to use compose recursively. I'd simply .reduce the args instead.
  • @deceze I expect compose to return a function. But when I call the function returned by compose, I get it's body as a string. That's what I'm confused about. edit: Ah okay, I see what you mean. Thanks!
  • compose(args.slice(1)) You don't actually call the function returned by compose here as you do in the initial call, you use the function as the argument to args[0] instead of the result of calling it.
  • No, the crux is at args[0](compose(...)). This passes a function to (n) => n + 1, which concatenates 1 to the function body.
  • @deceze Thanks a lot, that makes a ton of sense, mystery explained!