Home Courses Anonymous Functions in JavaScript

Anonymous Functions in JavaScript

Anonymous functions are those functions that do not have any name. Just like an anonymous call or anonymous email has no identity, similarly, these functions also don’t have a defined name.


What is an Anonymous Function?

An anonymous function is a function without a name, and it is usually stored inside a variable.

Example:


const add = function(a, b) {
return a + b;
}

Here:

  1. The function has no name
  2. It is assigned to a variable add


Calling the Function:


console.log(add(2, 2)); // Output: 4


Anonymous Function vs Function Expression

  1. Both are stored in variables
  2. The difference is:
  3. Function Expression can have a name
  4. Anonymous Function has no name


Where Do We Use Anonymous Functions?

Anonymous functions are mostly used as callback functions.

Example:


function operations(fun) {
let x = 10;
let y = 20;
console.log(fun(x, y));
}

const add = function(a, b) {
return a + b;
}

const sub = function(a, b) {
return a - b;
}

operations(add); // 30
operations(sub); // -10

Here:

  1. operations is taking a function as a parameter
  2. add and sub are passed as arguments
  3. These act as callback functions


Another Example: setTimeout


const onTime = function() {
console.log("on time called");
}

setTimeout(onTime, 2000);

  1. setTimeout takes a function as a parameter
  2. That function is executed after a delay


Hoisting in Anonymous Functions

Anonymous functions behave like function expressions.

  1. You cannot call them before declaration

add(); // Error

const add = function(a, b) {
return a + b;
}


Difference: Named Function vs Anonymous Function

  1. Named functions can be called inside themselves (useful in recursion)
  2. Anonymous functions cannot be called internally because they don’t have a name
  3. Debugging is easier with named functions
  4. Anonymous functions are commonly used in callbacks


Share this lesson: