JavaScript - Closure - Three examples for the price of one

It is possible to pass arguments on a parent function to add these arguments on the nested one.
Can you believe this?
One calls this a closure.

Let's start with an easy example without any closure:

// test1
function fTop(a) {
  return a;
}

var fake1 = fTop(1);
var fake2 = fTop(2);

alert(fake1 + fake2);

And the result is...?

3 of course!

OK, it was easy.

Let's continue with this new example, a little more astonishing:

// test2
function fTop(a) {
  function fMiddle(b) {
    return a + b;
  }
  return fMiddle;
}

var fake1 = fTop(1)(3);
var fake2 = fTop(2)(4);

alert(fake1 + fake2);

I can see you hesitating and saying: "This example can not work".

Ahah!! Of course it works!

The result is: 10.

Why?!
Because the numbers 1 and 2 are the arguments of the fTop() function and  the numbers 3 and 4 are the arguments of the fMiddle() function.
So the first step is the fTop() function that returns fMiddle.
This fMiddle acts as a variable that stores the variable 1.
Then the fMiddle() function is executed and the variable a is here, in memory.
So the fMiddle() function is able to return the result of a + b.

To confirm this behaviour, we will create a last example, with 3 levels:

//test3
function fTop(a) {
    function fMiddle(b) {
        function fBottom(c) {
            return a + b + c;
        }
        return fBottom;
    }
    return fMiddle;
}

var fake1 = fTop(1)(3)(5);
var fake2 = fTop(2)(4)(6);

alert(fake1 + fake2);

And of course it works!

The result is 21.

Of course, all these examples can be done with a different way.
Let's take the test2 sample to retype a new one:

//test2.2
function fTop(a) {
  function fMiddle(b) {
    return a + b;
  }
  return fMiddle;
}

var fake1 = fTop(1);
var fake2 = fTop(2);

alert(fake1(3) + fake2(4));

Result: 10.

Maybe a more readable way, or not, depending of your programming vision.

Anyway, a great behaviour of JavaScript laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.