Like other advanced languages, JavaScript also supports anonymous functions. From the word anonymous, it is clear that when a function has no name, that function is called an anonymous function.
Also Read: Functions In JavaScript β Simple Explanation
In this article, we will cover what is an anonymous function in JavaScript, how we can use them, their syntax and basic usage.
This is a named function, aka a function declaration
Functions generally allow codes to be reusable instead of typing the same thing every time, we will just call the function.
Functions conform with the principle in coding: βDRYβ. DRY is a term that stands for Donβt Repeat Yourself. The opposite of DRY principle is βWETβ meaning We Enjoy Typing which is not good.
A JavaScript function is a block of code designed to perform a particular task.
To write a function in JavaScript, you will start by writing the keyword function
followed by the variable name and then (parameters for the function is put here) and {}
in which codes to be executed goes inside the curly bracket, for instance:
function namedFunction (a,b) { return a+b } console.log(namedFunction (2,2)); //4
The above function is called named function or normal function because it has a name or variable immediately after the keyword function
.
Also, for a function to be executed, it must be called or invoke. For instance, the above normal function will be called in the following way:
namedFunction(2,2)
which gives 4
as answer.
This is an Anonymous function, aka a Function expression
As for anonymous function, it has no name after the keyword function
. Although anonymous function has no name, but it can be stored in a variable and run essentially the same way.
The following shows how to define an anonymous function:
(function () { //... });
Note that if you donβt place the anonymous function inside the ()
, you will get a syntax error. The ()
makes the anonymous function an expression that returns a function object.
An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable.
An anonymous function is a function that is anonymous. It doesnβt have a name. However, it can be stored in a variable and run essentially the same way.
For example:
var sum = function (num1, num2){ return num1+num2 }
You will observe that the function has no name coming after it, that is why it is called anonymous.
In calling anonymous function, you are to call the variable name since there is no function name, then you can save it to a different variable if youβd like.
var sum = function (num1, num2){ return num1+num2 } console.log(sum(2,2)); //4
Since the whole assignment of the anonymous function to the sum
variable makes a valid expression, you donβt need to wrap the anonymous function inside the parentheses ()
.
Let’s see few other example of anonymous function:
Example 1:
let demo = function (){ console.log("Example of anonymous functions"); } demo(); //Example of anonymous functions
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.
Example 2:
button.addEventListener('click', function(event) { alert('Button is clicked!') })
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 event listener 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.
Also Read: AddEventListener – How To Use It
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!”.
Example 3:
let area = function(length, breadth){ return length * breadth } let x = area(10,5) console.log("Area of the rectangle is = ", x); //Area of the rectangle is = 50
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.
Besides the syntax, how are they different?
Function declarations are hoisted. What does it mean?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the function, if defined in a function, or the top of the global context, if outside a function.
That’s why in the example below, the function call works even before the function declaration appears.
console.log(namedFunction (2,2)); //4 function namedFunction (a,b) { return a+b } console.log(namedFunction (2,2)); //4
Anonymous functions, on the other hand, are not hoisted. As you can see, when we call the sum
function before the function declaration, we get an error. When we call it after the declaration, it works.
console.log(sum(2,2)); //TypeError: sum is not a function var sum = function (num1, num2){ return num1+num2 } console.log(sum(2,2)); //4
Why would you use an anonymous function instead of a named function?
Sometimes you don’t need to name a function because you are just going to use it as a callback to another function. Since you are not using it again elsewhere, it doesn’t need a name.
So, in practice, you often pass anonymous functions as arguments to other functions.
For example:
setTimeout(function() { console.log('Execute later after 1 second') }, 1000);
In this example, we pass an anonymous function into the setTimeout()
function. The setTimeout()
function executes this anonymous function one second later.
Immediately invoked function execution
If you want to create a function and execute it immediately after the declaration, you can declare an anonymous function like this:
(function() { console.log('IIFE'); })();
How it works.
First, define a function expression:
(function () { console.log('IIFE'); })
This expression returns a function.
Second, call the function by adding the trailing parentheses ()
:
(function () { console.log('IIFE'); })(); //IIFE
and sometimes, you may want to pass arguments into it, like this:
let person = { firstName: 'Sunil', lastName: 'Pradhan' }; (function () { console.log(person.firstName + ' ' + person.lastName); })(person); //Sunil Pradhan
This is an arrow function, a special type of function expression.
ES6 introduced arrow function expressions that provide a shorthand for declaring anonymous functions:
For example, this function:
let show = function () { console.log('Anonymous function'); };
β¦ can be shortened using the following arrow function:
let show = () => console.log('Anonymous function');
Similarly, the following anonymous function:
let add = function (a, b) { return a + b; };
β¦ is functionally equivalent to the following arrow function:
let add = (a, b) => a + b;
Conclusion
This short article provides a quick overview of anonymous functions in JavaScript. Hopefully it can serve as a quick reference the next time you start coding in JavaScript!
Happy Coding!
Resource
- Benchmark – Anonymous Function VS. Named Function
- JavaScript Anonymous Function – gitconnected
- Anonymous Functions for Private Namespacing in Your JavaScript Apps
Add comment