Search code examples
javascriptfunctionhoisting

Anonymous Javascript function or store within a variable?


There are multiple ways to invoke a javascript function, most of the time I'm using anonymous function as it can be trigger anywhere I like.

I can't seem to understand why use the variable method instead of the anonymous function. The main disadvantage for me is because of the hoisting issue....

Can anyone explain or provide a real life example when is it appropriate to store function within a variable?


Solution

  • If you want to use the same function in multiple places it makes sense to store it in a variable. This allows you to adhere to the DRY (Don't Repeat Yourself) principle.

    Imagine we had a simple validation function:

    function isPositive(val){
       return val > 0;
    }
    

    Instead of inlining this anonymous function everywhere I need to validate, it is much easier to store the function in a variable for future use.

    var isPositive = function(val){  return val > 0;}
    

    This provides me with two major benefits. First, if there is an issue in isPositive I can fix the issue at one spot and all invocations of the function will use the updated behavior. Second, it prevents me from messing up the function somewhere in the code when I'm retyping it for the 100th time.