Search code examples
javascriptanonymous-functionfunction-expression

Declaring functions in JS: Named and Unamed expression


Recentley I began looking into the JS library Typeahead as a solution to a predictive search box. However upon looking at the code to implement it I began to look into things a little deeper and it led me to declaring functions in javascript.

I understand that there are 3 primary ways of achieving this:

  1. Function Declarations
  2. Function Expressions
  3. Function Construcros

Looking closely at function expressions it then led me to anonymous functions. My understanding of these is that they are effectively a function expression without a name?

My question is around the difference between named function expressions and anonymous functions, why would I opt to using an anonymous function? What are the benefits (if any) to an anonymous function?

If you see below ( I know it's a very VERY simply example) it appears that they pretty much do the exact same thing? I can't seem to differentiate between them.

 //Named function expression
   var add = function add(a,b){
       var result = a+b;
       console.log('adding ' + a + ' and ' + b + ' = ' + result);
   }
   add(6,2);

   //Anonymous function expression
   var multiply = function(a,b){
       var result = a*b;
       console.log('multiplying ' + a + ' by ' + b + ' = ' + result);
   };
   multiply(10,6);

   //Named function called immediately
   var divide = function myfunction(a,b){
       var result = a/b;
       console.log('dividing ' + a + ' by ' + b + ' = ' + result);
   }(10,5);

   //Anonymous function called immediately
   var subtract = function (a,b)
   {
       var result = a - b;
       console.log('subtracting ' + b + ' from ' + a + ' = ' + result);
   }(10,5);

On a side note this was the question that led me to write this one: Explanation of Typeahead.js substringMatcher function

In the code the author uses an anonymous function. Anyways I'd really appreciate if someone could clear this up for me. Also before you ask I have indeed googled this and been brought to various different sites outlining the differences but I'd prefer to ask the community here.


Solution

  • Named function expressions can call themselves recursively. Also, their names show up in stack traces which can help with debugging.

    Beyond that, it's just a code style thing.