Introduction
William Shakespeare once said that “What’s in Name?” but as a developer, we can disagree. We have to name variables, classes, functions, constructors, and others. Managing all the name and their scope within the code can be hectic and can create further complexity in the code.
Naming a function can be solved with the anonymous function in JavaScript(other languages also have an anonymous function). Anonymous means an entity having no name or identity. The anonymous function is a function that has no name and can execute immediately after defining them.
In this article, we are going to look into the following topics:
- Named function
- Anonymous function
- Arrow function
- And their examples So, let’s get started.
What is Named Function?
Before getting to the Anonymous function, let’s discuss the Named function. Named functions are general function that has a name. As you might know, functions are blocks of code that are used to perform a particular task.
Syntax of a Named function in Javascript
Named function declared with the keyword function
followed by the name of the function. The name will be followed by a pair of parenthesis and then pair of curly brackets. Within the curly brackets, we define the code. These functions can be invoked with the use of the name of the function.
function myFunction(){
console.log(“It’s a Named Function”)
}
myFunction();
Benefits of Named Function
- There are many use cases of named functions. They have a variety of benefits including
- A named function can be reusable
- It can make code readable as it has separation between function and invoking
- In case of error handling, the compiler will give an error with the name of the function, making it easy to handle the error
- You can define the named function after invoking it. While interrupting the code, JavaScript will move the function at the top. This is method is called Hoisting.
Drawbacks of Named Function
- Managing Different names of functions, variables, components, and all can be hectic.
What is Anonymous Function?
Solving the problems of Named functions, the Anonymous function came into existence. You already know that an anonymous function does not have a name. Let’s look into the syntax of it.
(function () {
// Code
})
We define an anonymous function within the parenthesis. After that, we have the keyword function
to define any function followed by the pair of parentheses but without the name. Then the pair of curly brackets, within those, we can define the code of the function. This is the syntax of an anonymous function in JavaScript.
Implementation of an Anonymous Function in JavaScript
An anonymous function can be defined as mentioned above but for invoking, we need to store them in a variable. These variables can be of any data type such as var, let, and const. Using the const is widely used and recommended for a non-changeable variable, so we are going to use the const for storing the anonymous function in the variable. We use the name of the variable for invoking the function. Here is the syntax for implementing them in JavaScript
const myFuntion = (
Function () {
console.log(“Hello World!”)
})
myFunction();
You can also pass the argument in the Anonymous function. Here is the example
const myFunction = (function(str) {
console.log(str)
})
myFunction("Hello World!")
Use of Anonymous Function in JavaScript
As we have seen the syntax and implementation of Anonymous functions in JavaScript, it’s time to learn about some use case scenarios of the anonymous function.
a. Using anonymous functions as arguments of other functions
JavaScript is a High Order language, which makes it able to pass functions as an argument to other functions. Previously we used to pass the name of the function like this:
function myFunction(){
console.log(“5 second has passed”)
}
setTimeout(myFunction(), 5000)
As the Anonymous function does not have a name, we can pass directly as the arguments to other functions. We do not need explicitly declare the function outside the argument. Here it goes like
setTimeout(function() {
console.log(“1 sec has passed”)
}, 1000)
This makes our code even cleaner as one-time used functions are directly defined as the argument.
b. Immediately invoked function execution
With the normal function, we have to define it and then invoke it for its execution. An anonymous function can be declared and immediately invoked for its execution. You can see the code example here
(function(){
console.log(“Hello World!”)
})();
In the above, example, the anonymous function is defined as usual followed by pair of parenthesis. This parenthesis makes the function immediately invoked for the execution.
During the immediately invoked function, you can also pass the argument within the parentheses defined after the declaration of the function.
const firstName = "John";
const lastName = "Doe";
(function(){
console.log(firstName, lastName)
})(firstName, lastName);
What is Arrow Function?
The Arrow function was introduced to us in ES6 to simplify the anonymous function even more. This function also has no name but its syntax is different from a normal anonymous function.
The syntax of an arrow function is simple. We have parentheses, within that, we can pass the argument for the function. This is followed by the equivalent sign =
and a greater than sign >
, together making it =>
. After that, we can define the code in parenthesis or curly brackets. Parenthesis are used for a single statement and it will return that statement. For multiple statements, curly brackets are used. You need to explicitly define the return statement in this case.
The difference between the arrow function and the Anonymous function
An arrow function can be defined in a line, while in the anonymous function we need more than 3 lines for the execution of one statement.
// Anonymous Function
(function () {
// Code
})
// Arrow Function
() => (//Code)
Note: The above example is for a single statement.
Example of Arrow Function
Arrow functions do not have names but they can be stored in a variable as in the Anonymous function. This variable can be used for invoking the function.
const myFunction = () => (console.log("Arrow Funciton are awesome"));
myFunction();
As we see in the Anonymous function, the arrow function can also be passed as an argument to another function
setTimeout( () => (console.log(“5 second has passed”))
, 5000)
We can also pass argument in the arrow function as in named functions.
const name = (firstName, lastName) => (console.log(firstName, lastName));
name(“John”,”Doe” );
Conclusion
We have come so far from Named function to Anonymous Function to Arrow Function. All these types of functions have a variety of use cases in certain conditions. We have discussed many examples with arguments and benefits of using these functions.
All the above function is useful. I hope this article has helped you in deciding which function to use according to different scenarios. Thanks for reading the blog post.
Top comments (13)
A lot of confusion and incorrect information in this article. Many of your 'anonymous' functions are not anonymous functions at all
If you read the article, it's for storing the function in a variable.
This is not correct - you can declare a named function without a function statement, and immediately invoke it:
It is true that you cannot immediately invoke a named function created with a function statement, but not true that you cannot invoke a named function immediately after declaration.
Immediate invocation is possible because the preceding code is an expression whose value is a function - it has nothing to do with whether the function is anonymous or not. If you have defined a function using a function statement - then that statement is not an expression and therefore has no value that you can call.
Considering this, I like to thank you as I was not having the knowledge on this. I have updated the article as per your feedback.
Yes, but the very act of assignment makes those functions cease to be anonymous functions. They acquire the name of the variable/constant. This can be shown by checking the function's name:
Contrast this with an actual anonymous function:
After the initial declaration of the anonymous function, it can't be invoked later. For that, we have to store it inside a variable. That's I did above. This has led to having a name.
Again, this isn't really related to anonymous functions. To use ANY function (anonymous or otherwise) later - we need to store a reference to it somewhere - it doesn't matter if it is named or not.
It's also perfectly possible to store anonymous functions without them acquiring a name (so they retain their anonymity) - for example in an array:
It retains anonymity but still, you need to store it into a variable.
Not having a name has no bearing on this. It's equally possible to pass in a function expression that does have a name. This may actually be preferable sometimes as it may aid the reading of debug traces in some environments (where the name will be used for display purposes).
Definitely you just need to pass function it can be annonymous, named or arrow. But annonymous will be easy to implement. It will be mostly one time function, you can go with functions not having name.
There are a number of mistakes in this example. Firstly - it won't run because
myFunction()
should say justfunction
orfunction myFunction()
. Further,console
is misspelled and the message will display after 1 second, not one minute.Typo fixed.