When should I store a function into a variable?

Usually I'll only use a var funcName = function(){} when I would need to redefine the action(s) for that function later on. For example:

var foo = function(a){ return a * 2; }
var bar = foo(2);

foo = function(a){ return a / 2; }

bar = foo(bar);

Otherwise, for most purposes (assuming it's not a callback or a modifier) declaring a function "classically" is usually acceptable.


I default to the non-variable function onReq(){} version. It's not a concious decision I've made, but thinking about it brings forth these arguments:

  • It looks cleaner.
  • It is conceptually simpler: it's just a function, while the other is a function and a variable. It's a small thing, but I find it valuable none the less.
  • It assures me that onReq will always refer to that function body - one less thing to consider when reading the code. Sort of like marking a variable as final in Java.
  • Keeps me from "accidentally" replacing the function, causing unintended side effects elsewhere.

Here is an explaination:

There is a distinction between the function name and the variable the function is assigned to:

  • The function name cannot be changed, while the variable the function is assigned to can be reassigned.
  • The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement).

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope


I see that nobody mentioned (directly and practically - which seems this question is about) the reason for which I personally find most useful for storing functions in variables. That reason is dealing with a complex logic that requires a lot of choices (e.g. if's) to determine further course of action for which different functions should be called, possibly with different sets of inputs as well. It makes code cleaner when that further course of action is launched in just one place, at the end of our logic.

function fooA (input) {...};
function fooB (input) {...};
let chosenHandler;
let chosenInput;

// Here we establish which function is relevant
if (someCondition) chosenHandler = fooA;
else chosenHandler = fooB;

// Here we establish which parameter should be used
if (someOtherCondition) chosenInput = 'First input';
else chosenInput = 'Second input';

// Call chosen function with chosen parameters - one place, nice and clean
chosenHandler(chosenInput);

If we tried to call functions directly, the code would get much more messy and get the messier the more complex the logic is.


According to John Resig's JavaScript as a First Language article, your first code block is considered as best practice.