0

I am trying to understand anonymous functions but having a hard time. The function below is an anonymous function but I'm not sure how it would get called or used. I have looked all over the web but have not gotten a good explanation of how/when to use it. Please help.

    var area1 = (function() {
    var width = 5;
    var height = 2;

    return width*height;
}());

Thanks for any clarification that can be provided.

JustMe
  • 147
  • 2
  • 11
  • 1
    The function is defined and called afterwards. That's because there's `()` after the function's body `{...}`. I'm not sure what else is there to explain. – freakish Jul 27 '14 at 14:56
  • 1
    Here's another helpful link that I found: http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write – Anderson Green Jul 27 '14 at 14:57

1 Answers1

0

That is an immediately executed function expression. The function is defined, then executed right away (by the () after it).

The code has the same effect as:

var area1 = 10;

You can't use the function after that statement, because it only exists as an intermediate value, and the variable area1 is assigned the result of executing the function.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005