Explain named and anonymous functions in Javascript.


What is Anonymous Function?

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


var myFunc = function() {
	alert('Anonymous Function');

Use of Anonymous Function

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

3 Anonymous functions are commonly used for creating function expressions.

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,

function myFunc() {
  alert('Named Function');

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