Voice of a Developer: JavaScript Anonymous Functions - Part Twelve

JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.

Before moving further let us look at the previous articles of the series:

In the last article I covered functions in depth. Now, I will cover Anonymous Function in detail covering its advantages, disadvantages & differences.

Anonymous Function

We know what a function is and we need to understand what anonymous function is. Anonymous means,

A function without a name is an anonymous function. We store these inside a variable name. So, the invocation happens using the variable name.

Below is an example:

  1. var sum = function(a,b){return a+b;};  
  2. sum();  
Advantages of anonymous function

First advantage is that JavaScript allows you to pass anonymous function as an object to other functions. You don’t need to explicitly define the function before passing it as a parameter to another function. Example: below is distance calculator between two points. In method calculateDistanceMetres we’re passing an anonymous function.
  1. function calculateDistanceMetres(pointA, pointB, method) {  
  2.     var value =  method();  
  3.     return (pointB - pointA)*value;  
  4. }  console.log (calculateDistanceMetres(10,20, function(){return 1000;}));
Now, what if we don’t pass anonymous function then what will happen?
  1. console.log (calculateDistanceMetres(10,20));  
Then it will throw below error because method() cannot execute any code,

code

In order to solve above case, let us adjust our code which will cover both scenarios
  1. function calculateDistanceMetres(pointA, pointB, method) {  
  2.     if (method) {  
  3.         var value = method();  
  4.         return (pointB - pointA) * value;  
  5.     }  
  6.     else{  
  7.         return (pointB - pointA) ;          
  8.     }  
  9. }  
  10. console.log(calculateDistanceMetres(10, 20)); //output 10  
  11. console.log(calculateDistanceMetres(10, 20, function () { return 1000; })); //output 10000  
Other popular implementation of anonymous function is in popular frameworks & libraries. In Node.js http module createServer method accepts a function which is executed at each HTTP request.
  1. var http = require("http");  
  2. var server = http.createServer(function(request, response) {  
  3. response.write("Hello World");  
  4. response.end();  
  5. });  
  6. server.listen(1234);  
Second advantage is that it’s hidden from the outside world and only accessible to only programmer objects.

Example:
  1. var programmer = {    
  2.     lang:  'Javascript',    
  3.     browser: 'Chrome',    
  4.     getFullSpecs: function(){    
  5.         console.log(this.lang+ ' running inside ' + this.browser);    
  6.     }    
  7. }  programmer.getFullSpecs(); //only programmer object could access it
Third advantage it is widely used where you can pass like a callback. For example:
  1. $('#div1').click= function(){    
  2.     alert('clicked')    
  3. };    
  4. Or:  
  5.   
  6. function CallMe(callback)    
  7. {    
  8.     console.log('callback is called after');    
  9.     callback && callback();//check whether there is data for callback or not    
  10. }    
  11. CallMe(function(){alert('call me')});    
Disadvantages of anonymous function 
  • If you have large program then debugging is tough because you don’t know name of the function in call stack. The call stack will show it as anonymous function.

    Debug above program in Chrome & see Call Stack. You can notice anonymous function when the execution is at code function () { return 1000; }

    code

  • These functions cannot be reused.
  • These functions cannot be unit tested easily. Therefore, you may need to refactor the code.

Differences

Anonymous functionNamed function
This function gets created only after its declaration. Javascript doesn’t do hoisting like in the case of normal function.This function is loaded before any code executes, so the JavaScript engine does what is called hoisting [we will cover this concept in later articles].
You will get error if you try calling it before than its declaration.You can call the function before or after declaration anywhere in the code.

Summary

We need to balance between usage of anonymous & named function as it depends upon use case. Please share comments/feedback.

Read more articles on JavaScript:

Up Next
    Ebook Download
    View all
    Learn
    View all