8 minutes read

Frequently, during development, we only need to use a function once and do not require a specific name. We also pass a function as an argument to another function and do not need to call it again elsewhere in our code. And sometimes, we need to invoke the function we've created immediately. To cater to these needs, we can use anonymous functions. Let's delve deeper into this concept.

Anonymous function syntax

An anonymous function is a function that does not use an identifier when created. There is a basic rule: if a function does not have an identifier after the function keyword, then it is anonymous. Otherwise, it is named.

Let's look at a classic example of an anonymous function.

function () {
  return 'Hello world!';
}

An anonymous function is created here exactly like a named one, but the identifier is omitted.

const greetings = function () {
  return 'Hello world!';
}

greetings(); // 'Hello world!'

In this case, an anonymous function is created using the function keyword and assigned to a variable. Now, we can use this function using the variable to which we have assigned this anonymous function.

Hoisting is a mechanism in JavaScript in which variables and function declarations (using the function keyword) are moved to the top of their scope before the code is executed. When we create named functions with the function keyword, they are always "hoisted" to the top of their scope. When we assign an anonymous function starting with the function keyword to a variable, the hoisting mechanism does not work.

funcOne(); // 'One'

function funcOne () {
  return 'One';
}

funcTwo(); // Error

const funcTwo = function () {
  return 'Two';
}

It would be best if you remembered that an anonymous function is not available once created unless we assign it to a variable as a value. Functions are recommended to be assigned using const (after all, we are not going to change it).

You'll get an error if you define an anonymous function but leave it unused. You can immediately call it or assign it to a variable to avoid this.

Uncaught SyntaxError

Passing anonymous functions as arguments

There are several everyday use cases for anonymous functions in development. Often, we have to pass a function as an argument to other functions.

function alertMessage(text) {
  console.log(text());
}

alertMessage(function () {
  return "Hello world!";
});

// Hello world! will be printed in the console

In this example, we pass an anonymous function to another function as an argument, call the anonymous function in it, and use the result of calling it. We can assign an anonymous function to a variable and do the same.

function alertMessage(text) {
  console.log(text());
}

const textFunc = function () {
  return "Hello world!";
};

alertMessage(textFunc);

// Hello world! will be printed in console

Immediate execution of anonymous function

IIFE (Immediately Invoked Function Expression) is a function immediately called at the place of its creation. You might need it if you do not want to clog your code and if this function is not helpful to you in the future. After all, in an extensive application, it may be important not to create multiple unnecessary global variables. There are cases when you will need to call a function at the place of its creation immediately. In this case, you can use an anonymous function.

First, to create it, we must wrap the anonymous function in parentheses called the grouping operator. We usually use grouping operators to determine the precedence of evaluation in expressions. Then, put a pair of parentheses to call this function.

(function () {
  console.log('Hello world!');
})();

// Same thing just in arrow function syntax

(() => {
  console.log('Hello world!');
})();

// 'Hello world!' will be printed to the console

In the parentheses of the function call, we can pass any value provided in the anonymous function as an argument.

(function (text) {
  console.log(text);
})("Hello world!");

// 'Hello world!' will be printed to the console

Arrow functions

Arrow functions are a simpler syntax for anonymous functions. An arrow function consists of parentheses to pass arguments to the function, an "arrow" consisting of an equal sign and a greater than sign, and the function's body.

() => {
  return 'Hello world!';
}

// Same thing just in different syntax

function () {
  return 'Hello world!';
}

You can also assign an arrow function to a variable and use it.

const greeting = () => {
  console.log('Hello world!');
}

greeting() // 'Hello world!'

There are several other ways to simplify the arrow function. You can leave out parentheses if you have one parameter.

const greetings = text => {
  return text;
}

You can leave out curly braces and the return keyword if we have a straightforward expression.

const greetings = (text) => text;

// This function returns text which was passed as an argument

Conclusion

Functions are called anonymous if there is no identifier after their declaration after the function keyword. Otherwise, the function is named. The syntax of anonymous functions is almost the same as named functions, except for the absence of a function name.

We can pass anonymous functions as arguments to another function. This is the most common use case for anonymous functions in development. Anonymous functions must be assigned to variables or called immediately after creation using IIFE (Immediately Invoked Function Expression). Otherwise, you will get an error. Arrow functions are the syntax for anonymous functions. They are more straightforward and concise in terms of syntax.

138 learners liked this piece of theory. 10 didn't like it. What about you?
Report a typo