Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    hgs
    hgs is offline
    New Coder
    Join Date
    Jan 2010
    Location
    Germany
    Posts
    83
    Thanks
    3
    Thanked 5 Times in 5 Posts

    anonymous functions versus named function

    Hi

    Is there a difference in performance or memory consumption, if i create many anonymous functions in a loop like

    for (i=0;i<n;i++){
    element.onchange=function(){
    // some code
    };
    }


    or doing it like


    function myfunc(){
    // some code
    }
    for(i;i<n;i==){
    element.onchange=myfunc;
    }


    My feeling is that the second version is 'better" .
    Am i Wrong ?


    Regards
    Heinz

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,662
    Thanks
    6
    Thanked 1,006 Times in 979 Posts
    The only difference in this case is that you can re-use the named function while the anonymous one would have to be redefined everytime (in which case the performance would suffer). However, which way to go depends on the application.

  • #3
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    Have you heard the term 'Carpool', which is sharing a ride by multiple persons going to same location/direction. Recollect the advantages of using carpool.

    Now, consider named function as the 'Carpool' wherein multiple DOM objects are utilising/ reusing the named function, similar to multiple persons sharing a ride.

    So, its better to use named function for doing the same things (or similar things) multiple times.

    Hope this clarifies your doubt.

    Regards,
    Niral Soni

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,438
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    Actually, we had quite a discussion on this just last week.

    Apparently, the answer depends on the browser. Although perhaps it shouldn't. The ECMAScript standard says that all identical functions can be (and should be, though the "should" is less clear) represented by a single function that is shared.

    And some browsers apparently do exactly that. Meaning that, unless you used your function myfunc in some place *OTHER* than shown here, the two sets of code you showed are identical. All those supposedly separate anonymous functions will actually all be automatically rolled into one implementation by the newer and smarter browsers.

    However, it does seem true that there are enough older browsers out there that do *NOT* do this that the second approach is the better one in the near future.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Does it make if a difference if we name the function?

    Code:
    for (i=0; i<n; i++) {
        element.onchange = function somename() {
        // some code 
        };
    }
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by AndrewGSW View Post
    Does it make if a difference if we name the function?

    Code:
    for (i=0; i<n; i++) {
        element.onchange = function somename() {
        // some code 
        };
    }
    Yes, there are some browsers that don't understand named functions in assignments and so those browsers will fail to run the code.

    It is best to avoid using named functions at all. Assigning anonymous functions to variables allows for far greater flexibility and can be used in many places where named functions are not permitted (such as inside an if statement).

    The better version of the OP's original code is:

    Code:
    myfunc = function(){
     // some code
     }
     for(i;i<n;i++){
     element.onchange=myfunc;
     }
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by AndrewGSW View Post
    Does it make if a difference if we name the function?

    Code:
    for (i=0; i<n; i++) {
        element.onchange = function somename() {
        // some code 
        };
    }
    no, it's still a function expression instead of a lexical-hoisting function statement. the only place somename could be seen in a your function expression is inside the function.

    named functions are easier to debug than digging through 50 different anonymous() calls in a exception stack or firebug trace.

    i think for that reason alone, it's better to use named function statements.

    how to spot the diff?
    if the char to the left of the word function is a line-terminator or semi-colon, and there is a white-space after "function" followed by /[a-z_$]+/i before the opening paren, it's a statement.

    almost always, the chars to the left of the word function is whitespace and/or "=" in function expressions, which may or may not have an internal name.


    i recommend giving even function expressions names for self-documentation, easier maintenance, and more-precise debugging information when you need it most.
    Last edited by rnd me; 01-07-2013 at 09:39 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by felgall View Post
    Yes, there are some browsers that don't understand named functions in assignments and so those browsers will fail to run the code.
    i don't see how a name or lack of name makes any difference at all to a function expression in any browser i've ever used. such a browser would not meet the spec.

    can you give an example?
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    i don't see how a name or lack of name makes any difference at all to a function expression in any browser i've ever used. such a browser would not meet the spec.

    can you give an example?
    Three examples:

    Named functions cannot be used in expressions in IE8. You can either use a named function outside an expression or an anonymous function inside an expression in that browser but cannot give the function a name and assign it in the same statement and have it run in that browser. IE8 runs jScript rather than JavaScript and so isn't required to comply with the JavaScript spec as it complies with the jScript spec which doesn't allow named functions in expressions.

    Self executing named functions do not work in IE8 or Safari 2.

    You cannot return a named function in IE8 or Safari 2.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    almost always, the chars to the left of the word function is whitespace and/or "=" in function expressions, which may or may not have an internal name.
    Just to mention other possibilities though:

    Code:
    something = (function () {
        // immediately invoked function expression (IIFE)
    })();
    
    get: function (arg) {
    // attribute (method) assignment.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,333
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by felgall View Post
    Named functions cannot be used in expressions in IE8. You can either use a named function outside an expression or an anonymous function inside an expression in that browser but cannot give the function a name and assign it in the same statement and have it run in that browser. IE8 runs jScript rather than JavaScript and so isn't required to comply with the JavaScript spec as it complies with the jScript spec which doesn't allow named functions in expressions.
    Code:
    var sum=function SUM(x,y){return x+y;};
    alert(sum(4,5)==9)


    Quote Originally Posted by felgall View Post
    Self executing named functions do not work in IE8 or Safari 2.
    Code:
    (function doSum(){
    
      var sum=function SUM(x,y){return x+y;};
      alert(sum(4,5)==9)
    
    }());
    Quote Originally Posted by felgall View Post
    You cannot return a named function in IE8 or Safari 2.
    Code:
    alert (function doSum(){
      function SUM(x,y){return x+y;};
      return SUM;
    }());

    all three code boxes test in IE10 as IE8, which is supposed to be jScript mode. the engine can be verified by the following test:

    Code:
    "v"=="\v" // true in jScript, false in ECMA5
    i don't have safari2, but i doubt anyone would miss that 7 year old browser...

    if indeed my tests don't pan out on a "real" copy of IE8, i'll concede the point, but from what i can tell you're wrong in all three examples.

    i tested your if statement claim and both IE8(via IE10) and chrome show 3 here:

    Code:
     alert ( a() );
    
    if(function a(){return 1;}){
      function a(){return 2;}
    }else{
      function a(){return 3;}
    }
    and both throw as expected on this code:
    Code:
    alert( a() );
    
    if(function a(){return 1;}){
      var a=function a(){return 2;}
    }else{
      var a=function a(){return 3;}
    }
    maybe i'm misunderstanding your claims.
    if you can show code describing what you say won't work i'd be very interested.
    i do think that basic IE8 jscript should not be walled-out by a fundamental pattern, at least not just yet.
    still, i can see no evidence to support your claim, so i must shift the burden of demonstrativeness to you.
    Last edited by rnd me; 01-08-2013 at 07:12 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,438
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    well, yes. But attribute assignment is just "syntactic sugar".

    There's no difference semantically between
    Code:
    var f = new Object( );
    f.get = function( arg ) { ... }
    and
    Code:
    var f = {
        get : function( arg ) { ... }
    }
    Just two different syntaxes for acconplishing the same semantics.

    Don't get me wrong, the latter code this is very nice syntactic sugar to have available, but if it didn't exist you could live without it.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •