Anonymous functions in JavaScript

Manikum - May 31 - - Dev Community

Anonymous functions are the functions without name and later can be assigned as a value to a variable, but it will not be anonymous any more. And declared using two methods:-

  • Function expression
  • Arrow Function

Function expressions

These are the functions that are created using an expression syntax. And it also has two types:-

  • First - If used without assigning to a variable:-
(function(param, [param2]) {
    console.log("I m alone and anonymous");
})
Enter fullscreen mode Exit fullscreen mode
  • Second - If assigned to a variable:-
const funcName = function(param,[ param2]) {
    console.log("Yey, I am commited now and socialized");
    }
Enter fullscreen mode Exit fullscreen mode

Arrow functions

These are shorthand function expression syntax and has some features also

  • First- without binding:-
((param, [param2]) => {
    let info = "Use curly brackets for multiline statements";
    console.log(info);
})
Enter fullscreen mode Exit fullscreen mode
  • Second - With binding:-
const funcName = (param, [param2]) => {
    let info = "Why devs call us first class citizen";
    console.log(info);
}
Enter fullscreen mode Exit fullscreen mode

Arrow functions don't have their own "this" they get it from the outer context(object) where they have been defined. And if is one liner doesn't need return directive.

Now some intruction for the use

  • If using them without assigning to a variable always use parantheses.
  • And to immediately call add trailing() at the last of the function expression, known as Immediately invoked function expression IIFE.
  • Mostly used as callback functions
.