locked
Javascript Functions

    Question

  • I am working on a HTML5 and Javascript app to learn on but I have a question on the functions.  This is a little confusing because I come from a C# background.

    What is the difference between the two below functions and why would I use one over the other?

    function foo() {

    //some code

    }

    or

    var foo = function() {
         //some code
    }

    -Thanks

    Tuesday, January 08, 2013 2:24 PM

Answers

  • The first declaration defines the function within a scope, could be Global, and allows you to call that function from within that context but the values or variables within the function don't change unless they reference a parameter or another Global value.

    The difference is that the second function declaration can be used within another function to use in, for example, a Promise or as parameter and is subject to Closure. You can use this type of declaration for functions that depend on values or variables that are dynamic on some context, for example:

    //reading some random data from a webpage with WinJS.xhr
    function ReadData(someUrl){
    var handler = function(result){
        //read the data from the result.responseText
    console.log(someUrl+" > readed data: "+result.responseText);
    }
    WinJS.xhr({url:someUrl}).done(handler);
    }

    When the "handler" dynamic function is created, it contains the value of "someUrl", once the xhr is finished getting the contents of the site (for ex. "http://www.microsoft.com") it displays its raw content plus the value of the "someUrl" parameter. If you call the function with a different parameter, the "handler" will be created dynamically with the new value.

    Trying to accomplish this with a Globally declared function would be quite harder.

    • Marked as answer by LluvianBlack Thursday, January 10, 2013 2:38 PM
    Tuesday, January 08, 2013 5:03 PM