Question

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?

Was it helpful?

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.

OTHER TIPS

If it is in a variable, I can access the function from anywhere, and as often as I want.

If you want to have the same action happen from multiple places. Like this maybe:

var renderPage = function() {
    // about 20 lines of render code        
}

$(window).on('resize', renderPage);
$('.my_btn').on('click', renderPage);

// render to initialize page
renderPage();

Not using variables here would turn into a mess real quick:

$(window).on('resize', function() {
    // about 20 lines of render code
));

$('.my_btn').on('click', function() {
    // about 20 lines of render code
));

// about 20 lines of render code
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top