-2

Main questions: 1. How does f refer to r and t within the formula but no declaration for them anywhere in the code. Also the references appear to be cyclical. 2. Why is f2 set to f(x) what does that accomplish?

let x = 3;
let y = 7;
const f = function(r) { 
        return function(t) { 
              return x + y + Math.abs(r) + t; 
           } 
      };
const f2 = f(x);
x = 2;
alert(f2(17));

This code works but I do not understand what it is doing.

Thank you for your help.

  • `f` is a function that takes a parameter `r` and returns an anonymous function that takes a parameter `t` and returns the sum of the value of the closed-over variables `x` and `y` and the absolute value of `r` and t. Your code calls `f` with `x` (value == 3) and assigns the returned anonymous function to `f2` then sets `x` to 2 then alerts the result of calling `f2` function with 17. So it's `2 + 7 + |3| + 17` which is 29. – Jared Smith Mar 14 '20 at 21:10
  • Thank you. That helps a lot. I have not run into this particular use of functions before. – Jonathan Marshall Mar 14 '20 at 21:22
  • NP. You will again though, this is pretty common in every programming language that supports it. – Jared Smith Mar 14 '20 at 21:27

1 Answers1

0

How does f refer to r and t within the formula but no declaration for them anywhere in the code.

You can declare variables using function arguments. This is what they are doing here.

A simplified example:

function example(f) {
    console.log("f is " + f);
}

example("one");
example(2);

Why is f2 set to f(x) what does that accomplish?

It calls f(x) and assigns its return value.

That return value is the function after the return keyword.

Now f2 is a function.

See also How do closures work

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335