Skip to main content

#3 Anonymous Functions

I have seen interviewers asking a candidate to write down the anonymous function on a paper before them. So, this post is for those candidates. Cheers!

Before we start to understand what is an anonymous function, we need to first understand the different ways of creating a function in JavaScript.

There are two ways to create a function:

1. Function declaration

2. Function operator

So, let's start with function declaration.

When you have a function keyword in the beginning of the statement and the function name following it, it's a function declaration. 

<script>
function callMe()
{
    console.log("I am a function declaration");
}
callMe();
</script>

Output:
I am a function declaration

Now, below is the example demonstrating how the above function can be written using function operator.

<script>
var abc = function()
{
    console.log("I am a function operator");
}
abc();
</script>

Output:
I am a function operator

As you can see, the function() is not the first statement in the statement. This signifies that it's a function operator and not function declaration.

Which one should I use?

You must have heard hoisting in JavaScript. If not then no worries. Hoisting in simple English means to bring something up. Like flag hoisting on an Independence day! JavaScript also does this hoisting while parsing the code. Look at below examples:

<script>
function callMe()
{
    console.log("I am a function declaration");
}
callMe();
</script>

Output:
I am a function declaration

<script>
callMe();
function callMe()
{
    console.log("I am a function declaration");
}
</script>

Output:
I am a function declaration

First example is straightforward where you are calling a function after it has been declared. But what about second one? You are calling the function before it is declared and it's working fine without any error. It's not a magic. It's JavaScript implementing hoisting.

When JavaScript starts to parse your code, it finds all the functions declared and bring them up behind the scenes. For you callMe() is the first statement but for JavaScript after parsing it's the last statement in the second example.

So, all this hoisting is possible only when the functions are declared and not when the functions are created using function operator. Hoisting is not applicable to function operators.

Function operators are created at runtime. This means, whenever the function appears, it is created at that point of time unlike function declaration where the functions are hoisted. See the output of below example:


<script>
a();
var a = function()
{
    console.log("I am a function operator");
}
</script>


Output:
Uncaught TypeError : a is not a function

To remove the above error just bring down the a(); statement.

This means if you declare function inside if, switch, for loops blocks, be cautious because the function will be hoisted during parsing and you might not get expected outputs. So, better use function operator in such scenarios.

So, I hope you have understood the concept of function declaration and function operator. 


When you write a function using a function operator, you are creating anonymous function. It doesn't have a name. This means the anonymous functions are created when they occur in the code. 

Anonymous functions do not always have a name?

No it's not like that. You can have names.

<script>
var a = function callMe()
{
    console.log("I am a function operator");
}
a();
</script>


Output:
I am a function operator

Here the function callMe() is stored in a variable a. So you need to invoke the callMe() using a().

What is the benefit of having a name then? You can see in a below example how you can have recursive function. But remember that though it has a name, it's an anonymous function. It is 

<script>
var flag=1;
var a = function callMe()
{
    console.log("I am a function operator");
    if (flag==1)
    {
        flag=0;
        callMe();
       
    }
}
a();
</script>

Output:
I am a function operator
I am a function operator


Above is not the only case. This also helps while debugging because not all (written by other developers in your team) will have names for their anonymous functions. When you have names it's easy to track the named anonymous function in the logs.

Anonymous functions are widely used in JQuery and AngularJS. 

Comments

Popular posts from this blog

Characteristics of a Good Programming Language

Till now there are many high level languages which are very popular, and there are others, which could not become so popular in-spite of being very powerful. There might be many reasons for the success of a language, but one obvious reason is the characteristics of the language. Several characteristics believed to be important with respect to making a programming language good are briefly discussed below. Simplicity A good programming language must be simple and easy to learn and use. For example, BASIC is liked by many programmers only because of its simplicity. Thus, a good programming language should provide a programmer with a clear, simple and unified set of concepts which can be easily grasped. It is also easy to develop and implement a compiler or an interpreter for a programming language that is simple. However, the power needed for the language should not be sacrificed for simplicity. The overall simplicity of a programming language strongly affects the readability of the pr...

Angular 4 and Firebase Authentication: Email/Password

In our  previous  article we saw how to create authentication module using Google identity provider. Now we will see how to implement Email and Password authentication using Firebase. We will use Bootstrap form to create intuitive user interface for sign-up and login using Email and Password. Step 1: Create signUp component. ng generate component signUp Step 2: Create custom form in sign-up.component.html file. The result of above code: Step 3: Add two functions for creating the user and login using Email and Password in src/app/providers/AFAuth.ts file. Step 4: Call createUserWithEmailAndPassword function in service from sign-up.component.ts. Step 5: Update routing configuration in app.module.ts  to include signUp component. Step 6: Update Login form to have Bootstrap form. The result of the above code. Step 7: Enable Email/Password component in Firebas...

Angular 4 and Firebase Authentication: Setup

If you have come to this article, it means you are keen to learn new technology and that too Firebase. I love Firebase because it provides all basic but important features of any web application. Take for example, authentication, which is cumbersome and risky if not implemented with utmost care. And when we have the integration of Angular and Firebase, it becomes a lot easier for a developer to build such crucial modules in less time with minimal efforts. In this article we will create a simple Angular application using Firebase. I am going ahead with the understanding that you know the benefits of Firebase and have little knowledge about it. There are plenty of posts out on the web if you are behind. Step 1: Install Angular CLI (if not installed). npm install -g angular-cli Step 2: Create new Angular 4 project. By default now angular CLI will create Angular 4 project so you need not fret. ng new firebase-authentication Step 3: Check whether the ne...