Why and when do you assign an anony function to a var?

Discussion in 'App Development' started by blueraincap, Jan 11, 2024.

  1. In JS, I never really understand and never do the former. Why and when should it be used? How are they different?

    Code:
    var pimp = function(colour){console.log("I will eat that " + colour + " ass");}
    Code:
    function pimp(colour){console.log("I will eat that " + colour + " ass");}
    It seems to do with Hoisting and Closure?

    https://cs3110.github.io/textbook/cover.html
     
    Last edited: Jan 11, 2024
  2. You can pass the function object to other functions, which can then call the object without having to hard the code to use a specific function. For example, if you implement a sort() function, you could pass compare function to sort() as an argument which compares two items used by the sort(). Then you could pass compare function to either to have items sorted by ascending or descending order, or do some more complex operations upon the item comparison.
     
    beginner66 likes this.
  3. Snuskpelle

    Snuskpelle

    While JS is not my language and it varies a bit over languages, in general you use the anonymous form to pass functions as arguments for very simple cases where writing the named function is overkill. I.e. in particular a case where you don't even bother to put it into a var:

    CallMyFunction(function(colour){console.log("I will eat that " + colour + " ass");});

    (At least in C#, you can still put a named function into a delegate var, I don't know if that's the case for JS.)

    Named functions tend to have easier to follow callstacks... So you should really only use anonymous form when it's bleeding obvious within the block you're in where the anonymous function is... unless of course JS requires the anon form for being put into variables.
     
    MarkBrown likes this.
  4. 2rosy

    2rosy

    as stated, can be used for callbacks. search for lambdas or function pointers