0

What does this function return? I'm not familiar with this nomenclature.

let x = 2;
let y = 8;
const a = function(b) { return function(c) { return x + y + Math.abs(b) + c; } };

// Statement will go here

const fn = a(x);

For the above function, I understand the x+y part, but what is the b and c referred to in the second half? Is a(x) calling const a?

The only thing I found that refers to similar nomenclature is function x y a b in javascript, but the discussion doesn't talk about how to find what is returned. Maybe I'm not searching for the right thing and that's why my search only returned one thing that is similar.

Michele
  • 3,617
  • 12
  • 47
  • 81

3 Answers3

0

What you see here is called currying, something related, but different from partial application.

The point is to break down a function call taking multiple arguments into multiple function calls taking single arguments.

In this case, a is a function that returns a function that returns the result of adding x, y, the absolute of b (coming from the call to a) and c (coming from the call to the return value of a).

Andre Nuechter
  • 2,141
  • 11
  • 19
  • "a form of a thing called partial application" --- currying **is not** a "form" of a partial application. Partial application is a result of partially applying a curried function. To reiterate the OPs example: `fn` is a partially applied `a`, which is a curried function. – zerkms Dec 01 '19 at 19:42
0

a is the result of a function that accepts an argument, b. That function returns another function that accepts an argument c and returns x + y + c plus absolute value of b.

let x = 2;
let y = 8;
const a = function(b) {
  console.log({
    b
  });
  return function(c) {
    console.log({
      c
    });
    return x + y + Math.abs(b) + c;
  }
};

// Statement will go here

const fn = a(x);

fn(12) // will have b=2 and c=12
aprouja1
  • 1,800
  • 8
  • 17
  • 1
    Are you saying that c is what is passed as x in a(x)? So would it be 2+8+2+2? I'm calculating that 14 would be returned from the fn call. – Michele Dec 01 '19 at 20:40
  • @Michele `c` is what you pass to the `fn` call. What you pass to the `a` call is `b`. – zerkms Dec 02 '19 at 09:03
0

It seems like a function pointer. function(b) accepts the parameter x that was passed into the function pointer a, this function pointer references function(b) but unlike normal functions which immediately returns a value, function(b) returns another function function(c) which ofcourse accepts one parameter and that parameter should be filled out when const fn was invoked.

My theory is that when you call fn for example fn(3) then you will get a result equivalent to 2 + 8 + Math.abs(2) + 3;

Without const fn you could also invoke a like a(2)(3) which I believe will yeild the same result.

Hope this helps.

junted
  • 11
  • 3