0

Im a newbie to Javascript and trying to understand how the anonymous function works,

When I run the below page, I get the "Fly to the sun" alert box. Not sure why does it get triggered

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
        </script>

        <script>
            function flytothemoon()
            {
            alert("Zoom")
            }

            var flytothesun = function(){
            alert("Fly to the Sun");    
            }
            flytothesun();
        </script>
    </head>
    <body>
        <input type="submit" onclick=flytothesun()>
    </body>
</html>
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 4
    There is no anonymous function here. You have defined a named function and also invoked it! – adarshr Nov 19 '13 at 13:30
  • Line `flytothesun();` is very highlighting... – Adriano Repetti Nov 19 '13 at 13:31
  • 1
    ...well what would you expect? – tckmn Nov 19 '13 at 13:32
  • 2
    @adarshr technically it is an anonymous function, it's just that the variable flytothesun references it, though that would probably be more confusing to the poster in this case. It is then invoked by adding the paranthesis () to the flytothesun variable however. See Tibos' answer below for a good explanation of these concepts – TommyBs Nov 19 '13 at 13:32
  • 2
    Why the massive downvotes and close votes? This is a very basic question - no need to hate on someone because they're a newbie. There is no 'minimal understanding' constraint nor it is 'unhelpful' or badly phrased. – Benjamin Gruenbaum Nov 19 '13 at 13:36
  • @adarshr There is,a reference to an anonymous function, created via a function expression, gets assigned to a declared variable, having a name. The function objects `name` property is indeed `undefined` – Moritz Roessler Nov 19 '13 at 14:14
  • Related: [`var functionName = function () {}` vs `function functionName() {}`](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Qantas 94 Heavy Nov 30 '13 at 00:27

4 Answers4

2
function flytothemoon() { // definition of flytothemoon
    alert("Zoom")
}

var flytothesun = function(){ // definition of flytothesun
    alert("Fly to the Sun");    
}
flytothesun(); // invocation of flytothesun

<input type="submit" onclick=flytothesun()> // handler

I annotated the code with 4 comments:

  1. Definition of flytothemoon. That section defines a function that can be used wherever in your code (even at lines before you defined it).

  2. Definition of flytothesun. That section defines a variable that references an anonymous function. You can use that variable to call the function, but only after the lines that define it are executed.

  3. Invocation of the flytothesun method. Using the reference at 2 you invoked the function. This is when the alert appears.

  4. Added function as handler. Your syntax is wrong here. It should be onclick="flytothesun()". That will also invoke the function, but only when the click event is fired on the input field (when you press the mouse button over the input).

Tibos
  • 27,507
  • 4
  • 50
  • 64
1

If you are trying onclick then you have forgot to give double quotes around function and dint provide any value to it (Try below html code):

<input type="submit" onclick="flytothesun()" value="click" />
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
1

If you haven't already, I strongly suggest reading the awesome article Named function expressions demystified, from which I'm going to cite through the Answer.

One of the two most common ways to create a function object in ECMAScript is by means of either Function Expression or Function Declaration. The difference between two is rather confusing. At least it was to me. The only thing ECMA specs make clear is that Function Declaration must always have an Identifier (or a function name, if you prefer), and Function Expression may omit it:

FunctionDeclaration :
function Identifier ( FormalParameterList opt ){ FunctionBody }

FunctionExpression :
function Identifier opt ( FormalParameterList opt ){ FunctionBody }

Your first function got declared, using a function declaration

function flytothemoon()  {
    alert("Zoom")
}

First of all, function declarations are parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated foremost any other expressions contained in a scope.

So, nothing special about it. A normally declared function, which can be invoked, using the functions identifier flytothemoon followed by parens ().

Your second function is a bit different, as such, that it is a function expression.

We can see that when identifier is omitted, that “something” can only be an expression.

What happens in the second case ?

To make the understanding easier, functions, are first class members in JavaScript, in the end, they are just objects, which can be assigned to a variable.

var flytothesun = function(){
        alert("Fly to the Sun");    
        }
  1. A new variable, flytothesun gets declared.
  2. Then the expression, initializing the variable, gets evaluated.
    1. The result of the expression is a reference to the anonymous function
    2. This reference, then gets assigned to your variable flytothesun

Remember, that functions are being invoked by parens ()?. Nothing else is happening in the line

flytothesun ();

You're simply invoking the function, which your variable flytothesun references.


As mentioned in the comments, you can also name function expressions, which's purpose and benefits are described pretty well in the article.
If you're interested, read it ;)

As it doesn't directly address a point in the question, i'll add two minimal (maybe not that practical) examples, only.

  • 1. Recursion. The functions reference is accesible via its identifier within the function.

var sixthParent = (function parent (el,n) { return n?parent (el.parentElement,--n):el})(someChildElement,6);

As you see, we can make use of named function expressions, by using the identifier to get our elements parent recursively

var results = [];
someAjaxReqeust (function callback (response) {
                     results.push (response.data);
                     if (response.has_more) {
                         someAjaxRequest (callback);
                     } else {
                         console.log (results);
                     }
                 });

In this case we used the identifier to pass the callback functions reference to our ajaxhandler, to make succesive ajax call if the response indicates there is more data.

  • 2. Debugging. The function expressions optional identifier will be included in the stacktrace in case of errors, which aids us in debugging. Without a name we would get <anonymous>

e.g

try {
    (function debug() {
        throw new Error("dummy")
    })()
} catch (e) {
    console.log(e.stack)
}
/*
Error: dummy
    at debug (<anonymous>:4:15)
    at <anonymous>:5:7
    at Object.InjectedScript._evaluateOn (<anonymous>:581:39)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:540:52)
    at Object.InjectedScript.evaluate (<anonymous>:459:21) 
/*  
Moritz Roessler
  • 8,542
  • 26
  • 51
  • You mention that for a function expressing, you *may* omit the identifier, which leads me to believe you may also provide it. As such ``var foo = function bar(){};`` is perfectly legitimate code. However, does the identifier make *any* difference in this case? Calling ``moo();;`` is possible, but ``bar`` remains undefined within the scope it was declared in. – Kippie Nov 20 '13 at 07:48
  • @Kippie That's indeed possible, and especially useful when it comes to debugging. Though it can be an aid for recursive functions, or paged ajax requests as well. e.g. you could give a callback for an ajax request a name, and make successive requests from within that callback, passing the original callback's reference via its identifier. I added two minimal examples to the answer as well – Moritz Roessler Nov 20 '13 at 13:12
  • Thanks, very much clear to me now :) – Kippie Nov 21 '13 at 08:03
0

Here is the explanation:

var flytothesun = function(){
    alert("Fly to the Sun");    
}

Above is the function from where you are getting the alert.

And below code you have define in the script part that means at the time of page load the function named flytothesun should call and that's why it is executing the alert.

 flytothesun();

Above code means calling the function when the page is loading. And due to that you are getting the message Fly to the Sun at the time of page load.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75