Anonymous functions use case

Why do we define anonymous function then pass it to a variable for further use? why can’t we just give it a name simply?

Why name if it you only use it once?

Most of the time, preference is idea. However, anonymous functions have important use cases.

One good example, is that it can be bound to a custom this object. This can be very powerful to control the context in which your application is running.

Another use-case is that, you can create a function and run it immediately its called without having to assign it a name.

Also, like he has mentioned, if you are naming an anonymous function, then u are using it wrongly, u may aswell just use an arrow function instead.

1 Like

i have seen cases where we pass it to variable then with the variable use that function again. so i just want to know why dont we give a name and use it instead?

@bikarajsingha do you mind giving an example please, maybe we are talking about different things


I understand what you mean though. Let me explain it like this.

An anonymous function has other more important use cases, some which I have explained above. However, because the syntax was introduced in Javascript, it can also be used to create a function as operational as a generic function. Therefore, people have also gained preference. Others like using anonymous functions all the time to keep uniformity in their code, others just because of preference. I have seen that happen before.

However, checkout this site for more examples and explanation.

I hope this helps or answers your question. Please let me know…

1 Like

yes thanks a lot it did

1 Like

@bikarajsingha Please mark it as the correct solution. To help others in the future. Simply click on the tick below my last answer.

you might want to check this out. It gives the most fulfilling response to your question:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.