An anonymous function is a function that doesn’t have a name or an identifier. Anonymous functions can accept inputs and return outputs just like standard functions. Let’s go through some uses of an anonymous function.

Uses of an anonymous function

  • If we want to use the function once or a limited number of times, an anonymous function may be syntactically lighter than a named function.
  • It is useful to help avoid needless global namespace pollution.
  • We can declare anonymous functions inline. Inline functions have the advantage of accessing the variables in the parent scopes.
  • The code seems more self-contained and readable.

Create an anonymous function

Declaration syntax for anonymous functions is pretty straightforward and similar to declaring a regular function. We can define declaraiton syntax inside a function and invoke it immediately or afterwards according to the requirement.

func( input parameter ) output parameter {
// Do some stuff
return values

If we don’t pass the input arguments, the function can access the variables defined in the parent. We can assign an anonymous function to a variable and use the variable to execute the function.

Let’s assign an anonymous function to a variable.

Get hands-on with 1200+ tech skills courses.