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");
})
- Second - If assigned to a variable:-
const funcName = function(param,[ param2]) {
console.log("Yey, I am commited now and socialized");
}
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);
})
- Second - With binding:-
const funcName = (param, [param2]) => {
let info = "Why devs call us first class citizen";
console.log(info);
}
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
Top comments (2)
If you assign an anonymous function to a variable, it ceases to be an anonymous function - it will acquire the name of the variable.
Y r right but, I mentioned it here just because to differentiate anonymous function from function that have an Identifier. So this article need a little add on. Thanks y mentioned.