In JavaScript, it is also possible to create anonymous functions. An anonymous function in JavaScript is a type of function that doesn’t have a name after the function keyword.
The term ‘anonymous’ means something that is unknown or has no identity. When we create an anonymous function, we declare it with no identifier after the function keyword.
Anonymous functions are also sometimes called as lambda functions in JavaScript. They are incredibly powerful programming features, and we can use them in any number of ways.
They are similar in structure to normal functions except it does not have name. Let’s understand the complete syntax of anonymous functions.
JavaScript Anonymous Functions Syntax
The general syntax to declare an anonymous function in JavaScript is as follows:
var varname = function(parameter-list) { // function body. };
In the above syntax, we have created an anonymous function with function keyword and parameter list and assigned it to a variable named varname. It is also possible to write an anonymous function in JavaScript like this:
function(parameter-list) { // function body. };
The above code is valid. Of course, we can never call this function because there is no pointer to it. Don’t forget to add ending (;) semicolon after the anonymous functions in JavaScript.
The main concentrated point is that there is no function name after keyword function. With a normal function, we use name after function keyword, as shown in the below code example:
function functionName(parameter-list) { // function body. } functionName(); // Calling function.
In this example, we have defined a normal() function, which is a normal function. This is the fundamental difference between an anonymous function and a normal function.
Let us consider an example where we will declare an anonymous function in JavaScript program.
Program code 1:
<html> <head> <title>JavaScript Anonymous Functions Example</title> <script> var firstName = function(name) { document.write(name); }; firstName("Tripti"); // calling anonymous function using variable name. </script> </head> <body> </body> </html>
Output: Tripti
In this example, we have defined an anonymous function that has no name and the function is set to a variable named firstName. The name property of the firstName variable will contain an empty string since the function has no name.
Syntax to declare Anonymous Function using Function Constructor
We can also define an anonymous function using a constructor. The general syntax is as:
var varname = new Function("para1", "para2", ... "paran", "function body");
In the above syntax, the first parameters are arguments to the function and the last parameter is the function body. The complete function is assigned to a variable.
Consider the following example below.
Program code 2:
<html> <head> <title>JavaScript Anonymous Functions Example</title> <script> // Declare anonymous function using constructor. var sum = new Function("x", "y", "return x + y"); document.write(sum(20, 30)); </script> </head> </html>
Output: 50
This is equivalent to the following code:
function sum(x, y) { return x + y; } document.write(sum(20, 30));
Anonymous Functions while creating Object
We can also assign an anonymous function to an object property. When we will do this, we can call that function using a dot (.) operator. Let’s consider a very simple example program:
Program code 3:
<html> <head> <title>Anonymous functions while creating object property</title> <script> // Creating an object property say m which has an anonymous function. var m = { msg: function() { document.write("Welcome to Scientech Easy"); } } m.msg(); </script> </head> <body> </body> </html>
Output: Welcome to Scientech Easy
In this example program, we have created an object with m property, which is an anonymous function. We do not need to name this function because we are calling it as object property.
Anonymous Functions while creating List
Let us consider an example program in which we will create two anonymous functions and adding them to an array. Then, we will iterate the array and execute the functions in the array list. Look at the following source code to understand better.
Program code 4:
<html> <head> <title>Anonymous functions while creating list</title> <script> // Creating an array say m which has a list of anonymous functions. var m = [ function() {document.write("One", "<br>")}, function() {document.write("Two", "<br>")}, function() {document.write("Three")}, ]; // Iterating array. for(var i = 0; i < m.length; i++) { m[i](); // Calling functions. } </script> </head> <body> </body> </html>
Output: One Two Three
Passing Anonymous Function as Parameter to Another Functions
This is one of the most popular use and you will find such code in the most professional site. Let us consider an example program in which we will pass an anonymous function as a parameter to another normal function. Let’s write code for it.
Program code 5:
<html> <head> <title>Passing Anonymous functions to other functions as a parameter</title> <script> // Creating a normal function with a parameter. function display(funct) { funct(); // Executing function as a parameter. } // Calling the normal function by passing an anonymous function as a parameter. display(function() { document.write("Passing anonymous function as a parameter to normal function"); }); </script> </head> <body> </body> </html>
Output: Passing anonymous function as a parameter to normal function
In this example program, we are passing anonymous function to another normal function named display. In the receiving function, we are executing anonymous function passed as a parameter.
This technique can be very convenient if we are defining single use function such as event handlers or object methods. Let’s take one more example in which we will pass a small anonymous function as an argument to the setTimeout() function.
Program code 6:
<html> <head> <title>Passing an anonymous function as argument to setTimeout function</title> <script> setTimeout(function() { document.write("Greetings"); },2000); </script> </head> </html>
When you will run this code, the following output will generate after a 2 second delay.
Output: Greetings
Anonymous Functions in Conditional Logic
In JavaScript, we can use anonymous function expressions in the if else statement. Let us consider the following example program.
Program code 7:
<html> <head> <title>Using anonymous functions in conditionally change behavior</title> <script> var shape; if(shape === "Circle") { shape = function() { return "Drawing circle"; } } else { shape = function() { return "Drawing rectangle"; } } document.write(shape()); </script> </head> <body> </body> </html>
Output: Drawing rectangle
In this example, we are assigning a different implementation to the shape variable based on a condition. This pattern can be useful if you are using with care. Overusing, the result can be unreadable and difficult to debug the code.
Use of Anonymous Functions in JavaScript
There are several uses of anonymous functions in object-oriented JavaScript programming. They are as:
1. Anonymous function helps us to avoid the naming conflicts and enables us to hide the code that applies to object, inside the object.
2. We cannot call anonymous functions because it has no name. But, when we assign it to a variable, we can call using variable name.
3. We can also pass an anonymous function to any other functions as an argument in JavaScript.
4. Another important scenario to define an anonymous function is for callbacks. Let’s create a JavaScript program in which we will use an anonymous function as a callback inside another anonymous function.
Program code 8:
<html> <head> <title>Passing an anonymous function as callback to function</title> <script> // Declaring the first anonymous function that uses another function reference inside. let funcWithCallback = function(func) { document.write(func()); } // Invoking previous declared anonymous function with an anonymous function. funcWithCallback(function() { return "Hello JavaScript"; }); </script> </head> </html>
When you will run this code, the following output will generate on the browser.
Output: Hello JavaScript
5. Anonymous function in JavaScript is quite useful when you are dealing with JavaScript events. For example, when user clicks on the mouse button on a web page, an anonymous function will be called and display a message on the web browser.
Program code 9:
<html> <head> <title>Using anonymous function when dealing with JavaScript events</title> <script> document.onclick = function() { window.alert("Hello JavaScript"); }; </script> </head> </html>
When you will run this code, and click on the web page, then the following output will produce on the web browser with help of pop up.
Output: Hello JavaScript
The above code is similar to the below code.
<script> function msg() { window.alert("Hello JavaScript"); } document.onclick = msg; </script>
As you can see in both script codes, an anonymous function is a handy way to handle the event without need to define function elsewhere and then invoke it.
Immediate Function Execution Expressions
JavaScript also allows us to declare a function and execute it as soon as we have finished declaring it. This technique is called an immediate function execution expression (IFEE).
In some books or websites, it is also called self executing or self invoking function. Let’s take an example program based on it.
Program code 10:
<html> <head> <title>Immediate function execution expressions</title> <script> (function() { document.write("IFEE", "<br>"); }()); // Another declaration. (function() { document.write("IFEE"); })(); </script> </head> </html>
Output: IFEE IFEE
We can use IFEEs to create a function scope around code initialization or for executing some functionality once. Here, declaring named function is a waste of memory.
Immediate functions can gain parameters and can also return values. Let’s create a JavaScript program in which we will use IFEE with parameters and return a value from an IFEE.
Program code 11:
<html> <head> <title>IFEE with parameter and returned value</title> <script> let returnedValue = (function(msg) { return msg; }("I love JavaScript programming")); document.write(returnedValue); // calling function. </script> </head> </html>
Output: I love JavaScript programming!
In this example program, IFEE accepts an msg argument, which is just returned from immediate function executing expression.
In this tutorial, you learned anonymous functions in JavaScript with various example programs. Hope that you will have understood the basic concept of anonymous function and how to use it in JavaScript program.
Thanks for reading!!!
Next ⇒ JavaScript Recursion⇐ Prev Next ⇒