Explain named and anonymous functions in Javascript.

javascript

What is Anonymous Function?

Anonymous functions in javascript are those functions that are created without any identifier or name to refer to it.

Example:

1
2
3
4
var myFunc = function() {
	alert('Anonymous Function');
}
myFunc();

Use of Anonymous Function

  1. Anonymous functions can be used as arguments to other functions.
1
2
3
setTimeout(function() {
  alert('hackinbits');
}, 1000);
  1. Anonymous functions are very useful in creating IIFE(Immediately Invoked Function Expression).
1
2
3
(function(text) {
  alert(text);
}('hackinbits'));

3 Anonymous functions are commonly used for creating function expressions.

1
2
3
let myFunc = function(text){
	alert('Inside Function expression');
};

What is Named Function?

Named functions are normal functions, with name or identifier to refer to it. For example,

1
2
3
4
function myFunc() {
  alert('Named Function');
}
myFunc();

Benefits of Named Function

Named function is very useful in javascript. Some of the benefits of using named functions are listed below:

  1. Named functions are very helpful in debugging, in knowing which function caused an error, as you will get the function name in the error log.

  2. Named functions are more readable, thus helping your code more understandable by other developers.

  3. Named Functions are easier to reuse and thus helps you in writing clear code.

Related Article

Share and support us

Share on social media and help us reach more people