Question

Here is a currying snippet from javascript patterns:

function add(x, y) {
    var oldx = x, oldy = y;
    if (typeof oldy === "undefined") { // partial
        return function (newy) {
             return oldx + newy;
        }
    }
    // full application
    return x + y;
}

ref: https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html

What is the point of local vars oldx and oldy?

Était-ce utile?

La solution

The variables oldx and oldy are completely unnecessary here; the code behaves identically without them:

function add(x, y) {
    if (typeof y === "undefined") { // partial
        return function (y) {
             return x + y;
        }
    }
    // full application
    return x + y;
}

The function being returned here has access to outer-scope variables regardless of whether those variables are declared with var or declared as formal arguments to an outer function.

Generally speaking, if x is a primitive, it might sometimes make sense to assign it to a new variable if you needed a copy of that value to alter independently of the original:

function foo(x) {
    var newX = x;
    newX += 7;
    // now newX and x are different
    // ...
}

However, that need does not exist in this code, so it's totally unnecessary.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top