Anonymous Function in JavaScript

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

"Anonymous" as the name suggests, is something that does not have any "name" or "identity". Similarly, anonymous functions in javascript are functions that do not have any name. Arrow functions are also anonymous functions with a compact syntax. Named functions are simply the functions, that have some name associated with them, you can consider them as the normal javascript functions we use.

There are several applications of anonymous functions, which we will explore as we go ahead in this article.

Scope

This tutorial will deal with the following topics, which we are going to discuss in great depth and examples:

  • Anonymous functions in JavaScript, syntax, usage, and examples.
  • Implementation and applications of anonymous functions.
  • Named functions, syntax, benefits, and examples.
  • JavaScript arrow functions, syntax, and examples.

Anonymous Functions in JavaScript

Anonymous functions in JavaScript, are the functions that do not have any name or identity. Just like, you have a name by which everyone calls you or identifies you. But, the anonymous functions, do not have any name, so we cannot call them like any other function in JavaScript.

Let us take an example:

function (){
    console.log("It will not run :p ");
}

Output:

Error: Function statements require a function name

Explanation:
If you try to run this function, it will result in an error saying Function statement requires a function name. And, that is completely legit, since ES6 says, you cannot have a function without a name in JavaScript. But then, how do we create anonymous functions, if they do not have any name?

Let's see how.

Syntax
Below given is the syntax for the anonymous function in JavaScript --

let variableName = function () {
    //your code here
}

variableName();     //Can call the anonymous function through this

Explanation:
We write the anonymous function in Javascript by writing function() followed by the parentheses, where we may pass the parameters, and skipping the function name. Then in a pair of curly braces {}, we write our desired code. Finally, we assign this function to a variable. We can later use the variable whenever we need the value of the anonymous function.

Does Anonymous Functions Always Need to Store their Value Inside Variables?
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name.

Also, we create anonymous functions in JavaScript, where we want to use functions as values. In other words, we can store the value returned by an anonymous function in a variable. In the above example, we stored the value returned by the function in the variable variableName.

Key Takeaways:

  • Anonymous functions do not have any name
  • We can write an anonymous function using the function keyword, followed by parentheses ().
  • We can write the function statements, just like we do for any other javascript function inside the curly parentheses {}.
  • We store the results returned by an anonymous function in variables.

Implementation of an Anonymous Function

Below given is an example to demonstrate the usage of the anonymous functions in JavaScript -

Example:

let demo = function (){
console.log("Example of anonymous functions");
}
demo();

Output:

"Example of anonymous functions"

Explanation:
In the above example, we wrote a function that logs "Example of anonymous functions", and please note we skipped the function name here. Then we assigned the function to a variable demo. Once we call demo() in line 4, we see it logs the value as expected.

So, this is how we write code for anonymous functions in javascript.

Now, let us take one more example to further illustrate our learning.

Example 2:

button.addEventListener('click', 
    function(event) {
    alert('Button is clicked!')
})

Explanation:
This is a very common use case of the anonymous functions in JavaScript. Here, we have attached an "event listener" to the anonymous function. An eventlistener is something, which responds to any event. An event can be anything such as when we click any button or hover on some component of any website. So, performing any such activities on a webpage triggers an event.

The above anonymous function is called whenever a button is clicked. The anonymous function takes a callback function event and listens to the event. And, once the button is clicked, it alerts the message "Button is clicked!".

Now, let's take one last example - Let us create an unnamed function, which calculates the area of a rectangle.

Example 3:

let area = function(length, breadth){
    return length * breadth 
}
let x = area(10,5) 
console.log("Area of the rectangle is = ", x);

Output:

 "Area of the rectangle is = " 50

Explanation:
In this example, we calculate the area of a rectangle. To do so, we create an anonymous function, which accepts two parameters - (length, breadth). After calculating the value, this function returns it to the variable area. To call that function, we simply call the variable, passing the arguments area(10,5) that the anonymous function expects. We store the result of this variable in x. Finally, we log the result into the console.

Function Expression Vs Function Declaration

A JavaScript function can also be defined using an expression. A function expression can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function.

They are of 2 types:

  • Named function: The named function expressions are like normal functions with name, but assigned to a variable.
  • Unnamed function: The unnamed function expressions, do not have any name. They are anonymous functions.

Example:

let x = function (a, b) {return a + b};

Function declaration is a normal function that has a function name and function statement. A declared function is “saved for later use”, and is executed later when it is invoked (called). Function Declarations must begin with “function” and have a name.

function num() {
return 100;
}

Use of Anonymous Functions in JavaScript

There are multiple uses of anonymous functions in javascript. Let us look at some very important and popular usage of the same.

Using Anonymous Functions as Arguments of Other Functions

Functions are called first-class citizens because, they can be passed as an argument to any function, or also returned by any function. The best use of anonymous functions is that they can be passed as arguments to other functions.

Let us briefly understand this using an example.

Example 1:

function greet(wish){
  console.log(wish() ,"everyone!");
}

greet(function(){
	return "Good Morning";
})

Output:

 Good Morning everyone!

Explanation:
In the above example, greet() is a function that expects another function as a parameter. So, we have passed an anonymous function to greet() where it returns "Good Morning". In the actual greet() function we get the value returned by the anonymous function in the parameter wish. Then, we log the value by calling the function wish() followed by our message. So, this is an example where we pass an anonymous function as the argument to another function.

Let us take another very popular example of passing an anonymous function to a function. You must have used setTimeout(), which is a method that expects a function and the number of milliseconds after which it will execute the function. Now, let us see how we can pass an anonymous function to setTimeout().

Example 2:

setTimeout(function () {
    console.log('I will run after 5 seconds!')
}, 5000);

Output:

//After 5 seconds
I will run after 5 seconds!

Explanation:
In the setTimeout() function, have we passed an anonymous function. It will run after a delay of 5 seconds since we have passed 5000ms as the second argument to the setTimeout() function.

Immediately Invoked Function Execution

Sometimes, we need to execute a function right after we declare it so that we don't need to go through the hassle of calling it. In these situations, anonymous functions are a great option since they execute right when declared.

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that gets invoked immediately. In simple words, it runs as soon as it is defined. It is a way to execute functions immediately, as soon as they are created.

Syntax

(function () {
  statements
})();

Explanation:
IIFE is a design pattern that is also known as a Self-Executing Anonymous Function and contains these major parts:

IIFE Design Pattern

  1. The first part of IIFE is the anonymous function -- check in the image, where we have only used the function keyword followed by parentheses - function (), and no name.
  2. The second part is the parameters list, where we can optionally provide a parameter
  3. The third part is the function body, where we can write our function statements, enclosed in curly parentheses {}.
  4. The fourth, and most important part is the () parentheses, which help to create the immediately invoked function expression. Using them, the JavaScript engine will directly execute the function.

Let us understand this better with an example.

Example 1:

(function(text) {
  alert(text);
})('Hi all! Welcome to our page.');

Output:

Output of IIFE

Explanation:
In the above example, we created an anonymous function, which is supposed to alert some messages. We defined the function and passed the appropriate parameter to it. Without having us call the function, it directly alerts the message once we execute our code.

Let us break the code in parts, and understand:

  1. First, the following defines a function expression:
(function(text) {
  alert(text);
})
  1. After that, we call the function by using the trailing parentheses (). We may optionally pass some arguments too to them if the function expects. In this example, the function expects a parameter so, we pass it.
('Hi all! Welcome to our page.')

Example 2:

for (var i = 1; i <= 5; i++) {
    (function (count) {
        setTimeout(function() {
            console.log(`Counted till ${count} after ${count} seconds`);
        }, 1000 * i);
    })(i);
}

Output:

"Counted till 1 after 1 second"
"Counted till 2 after 2 seconds"
"Counted till 3 after 3 seconds"
"Counted till 4 after 4 seconds"
"Counted till 5 after 5 seconds"

Explanation:
In this example, we implement a very good use case for the IIFEs. We have counted from 1 to 5 in JavaScript, putting a 1-second timer between every time we log a message. So, we iterate from 1 through 5, and pass the value of each iteration i in the IIFE:

(function (count) {
    // our code here
    })(i); //here in 'i' we pass value of each iteration

Then, inside our code, we use the setTimeout() for our operation. We maintain a timer, using i, which waits for 1000*i seconds before executing our code. After that, our function logs the message, with the count value and number of seconds after every second.

setTimeout(function() {
            console.log(`Counted till ${count} after ${count} seconds`);
        }, 1000 * i);
    

What Would Happen if we had not Used IIFE here?

In that case, our code looked like this:

for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        console.log(`Counted till ${i} after ${i} seconds`);
    }, 1000 * i);
}

Output:

 "Counted till 6 after 6 seconds"
 "Counted till 6 after 6 seconds"
 "Counted till 6 after 6 seconds"
 "Counted till 6 after 6 seconds"
 "Counted till 6 after 6 seconds"

So, in that case, we would get a result like this. It is because of the asynchronous code we have here. Whenever JavaScript encounters an asynchronous code, it postpones the callback's execution until the asynchronous task has finished. However, this is not under the scope of this article. But, you have seen how well IIFE solved this problem.

Function Expressions

A function expression is a function that is assigned to a variable. A function can be assigned to a variable because functions are first-class citizens in JavaScript.

Function expressions are of two types: named and unnamed. The named function expression has a name, parameter list, function statement, and an optional return value. The unnamed function expression is the anonymous function, which we have studied till now.

A function expression is very similar to a function declaration. But in function declarations, the name of the function is mandatory.

When are function expressions useful?

Function expressions are most useful when:

  • we want to pass a function as an argument to another function.
  • we want to use our functions as values.

Let us see examples of function expressions.

Example:

let demo = function (){
    alert("This is a function expression!")
}
demo();

Output:

This is a function Expression

Explanation:
It is a function expression without a name, hence can be called an anonymous function. We define this function and assign it to a variable. To call the function, we simply call the variable passing the required argument, followed by the (). Then, it directly alerts the message as expected.

Note: We can also have named function expressions.

What is Named Function?

As the name implies, named functions are functions that have a name associated with them in their declaration.

They are normal functions in JavaScript and are widely used.

Syntax

function name(parameter1, parameter2, parameter3) {
  // code statements
}

Explanation:

  • name: It is the name given to the function. It is mandatory and cannot be skipped in named functions.

  • param: The parameters we can pass to the function, which are separated by commas. These are, however optional.

  • statements: The statements comprising the body of the function.

Example:

function isPalindrome(string) { 
    const len = string.length; 
    for (let i = 0; i < len / 2; i++) { 
        if (string[i] !== string[len - 1 - i]) {  
            alert( `${string} is not a palindrome string`);  
        }  
    }  
    alert( `${string} is a palindrome string`);  
}  
  

isPalindrome("madam")

Output:

Madam is a Palindrome String

Explanation:
We declare the function, with the keyword function followed by the function name isPalindrome() and the parameter names enclosed in parentheses (string). Then we perform our operation inside the function. We call the function by using the function name and passing the required parameters to it. Then, after passing the string, it alerts the appropriate message.

Advantages of Normal Functions

  • Normal functions are easy to debug since we can directly know which function is causing the error because the function name will be listed in the error logs.
  • They are reusable since we can call them any number of times in our code and use them.
  • They are usually easy to read and understand.
  • Functions help in keeping code modular because we can divide every task into separate modules and utilize them later.

Arrow functions in JavaScript

Arrow functions are another great use case for anonymous functions in javascript. Arrow functions provide a shorthand way of declaring anonymous functions. They were introduced as part of ES6. They are very compact and allow us to write shorter, leaner code. However, there are certain limitations of arrow functions, which makes them not suitable to be used in some cases.

Syntax

Arrow functions are represented by an arrow-like structure, which is equal to the = sign followed by a greater than symbol >. In simple words, => is the representation for arrow functions.

We write the parameter list in (), followed by the arrow =>. After that, we write the function statements enclosed in parentheses {}.

Let us see the syntax in detail -

  1. If we have just one parameter:
param => expression

We can just write the parameter name(without any parentheses). If we have a very simple expression then we may skip the return keyword and enclose braces {} as well.

  1. We can have any number of parameters in the parameter list. If we have multiple parameters:
(param1, params) => expression

We can write the parameter name. And the code statement, for simple expressions, the return keyword may be omitted.

  1. We can also have 0 parameters, in that case, our syntax becomes:
() => expression
  1. If we have multiple parameters and multi-line code statement:
(param1, paramN) => {
    //line 1
    //line 2
    return value
}

In that case, we can write the parameters enclosed in braces, followed by the arrow => like symbol. And, write our code statements inside the curly braces. Also, optionally we may return the result as we do for any other javascript function.

Note: If we have a multi-line code statement, and suppose we need to return a value from the function, then it is mandatory for us to use the return keyword. However, we may skip return if we have a single line of code statement.

Examples of Arrow functions

After having studied in detail the arrow functions in JavaScript, let us now see some examples which will further enhance our understanding.

Example 1:

let x = a => a * a;	//Example of single param & single line code
console.log(x(10));

Output:

 100

Explanation:
In this example, we have an arrow function that expects only one parameter, a. So, we may optionally skip the enclosing parentheses of the parameter. Then we write the => symbol, representing an arrow. In the function definition, we compute the square of any number as a * a, which is a single line code, so again we may optionally omit the return keyword. We assign the result of this arrow function to a variable x. We call that variable passing the required argument to execute this arrow function.

Example 2:

function prompt(question, yes, no) {
  if (confirm(question)) yes();
  else no();
}

prompt(
  "Do you want to save?",
  () => alert("The file is saved!"),
  () => alert("The file is not saved!")
);

Output:

Do you want to save and file saved

Explanation:
In this example, we have used our arrow functions to display an alert based on the response given by the user. It is a simple yet very efficient use of arrow functions where we can prevent writing a completely new function for this simple task.

Example 3:

let x = (a,n) => {
    let pow = 1;
    for(let i = 0; i < n; i++){
	    pow = pow * a;
	}
    return pow;
};
console.log(x(10,3));

Output:

1000

Explanation:
In this example, we try to calculate the power of any number a raised to the power n. Please note that here we pass 2 parameters, so we cannot omit the () braces. Then we write the arrow-like symbol representing the arrow function. We compute the power and return the result. We assign this arrow function to the variable x. To call this, we can use the variable passing to it the arguments list: x(10,3).

How is it a Shorthand for Anonymous Functions?

A "shorthand" is a shorter way to express something already available in another syntax in our code. Arrow functions can be used to express the anonymous functions in a much shorter and more compact way. Let us take an example to understand this.

Suppose we have written this code using the anonymous function:

Example 1: Anonymous function

let x = function(){
console.log("Hello world!!")
};

We can write the same using arrow functions in a more compact way like this:

Arrow function:

let x = () => console.log("Hello world!!");

Explanation:
So, here we can omit the "function" keyword for arrow functions and also the curly braces for writing this single line of code, which makes arrow functions shorter and crispier to write. However, since they make our code one-liner, sometimes, it becomes a bit difficult for us to understand.

Example 2: Anonymous function

let square = function(x){
    return x*x;
};

Let us write this using arrow functions:

Arrow function:

let square = x => x*x;
// concise body syntax, implied "return"

Explanation:
This is a very short and simple written code in arrow functions, where we can omit the return keyword and the parentheses because of this one line of code and one parameter.

However, anonymous functions cannot be used in certain situations due to the limitations which come with them. It is not in the scope of the tutorial because it is a topic in itself.

Conclusion

Here we come to the end of the tutorial with a thorough discussion on anonymous functions in JavaScript, named functions, and arrow functions. Let us now recap what we have learned in this tutorial:

  • Anonymous functions in javascript are functions without any name or identity and are best used for cases when you want to invoke a function directly after defining it. Also, when you just want to use a function only once.
  • Anonymous functions in javascript are declared inline, and the code written is more readable to the users.
  • Named functions are given a name and are like the regular javascript functions. They are very helpful when you want to reuse your functions multiple times in your code. Also, they are pretty easier to debug than anonymous functions.
  • Arrow functions are a kind of anonymous function that provides shorter syntactical forms for normal javascript functions. They are concise to write and simpler to read.
Free Courses by top Scaler instructors