Jackques - 8 months ago 42

Javascript Question

I am having trouble wrapping my head around this (assuming I am missing something in there being a diffirence in calling an anonymous function directly or calling it by a variable.

Why does in the example below 0 set the variable 'total'?

`var adder = function (total) {`

// the following function is returned

// and assigned to adder

var inner_function = function (summand) {

total += summand;

alert(total);

}

return inner_function;

}(0);

adder(2); // returns 2

adder(3); // returns 5

But not when I call this anonymous function afterwards like so?

`var adder = function (total) {`

// the following function is returned

// and assigned to adder

var inner_function = function (summand) {

total += summand;

alert(total);

}

return inner_function;

}

adder(0);

adder(2); // -> 2

adder(3); // -> 5

Answer

You have two functions.

In the first example you assign the **return value** (i.e. the inner anonymous function) of the outer anonymous function to `adder`

.

In the second example you assign the outer anonymous function to `adder`

.

Since the value of `adder`

is a different function in each case, you get different results.

Source (Stackoverflow)