Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are anonymous functions a bad practice in JavaScript?

I was reading that using anonymous functions in javascript is bad practice, because it can make debugging a pain, but I haven't seen this for myself. Are anonymous functions in JavaScript really bad practice and, if so, why?

like image 306
stevebot Avatar asked Aug 11 '10 19:08

stevebot


People also ask

Does JavaScript support anonymous function?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

Why are anonymous functions useful in JavaScript?

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. 3. This function is useful for all scenarios. An anonymous function can be useful for creating IIFE(Immediately Invoked Function Expression).

Are anonymous functions slower?

Anonymous functions are faster than regular functions.

What are two common uses of anonymous functions in JavaScript?

One common use for anonymous functions is as arguments to other functions. Another common use is as a closure, for which see also the Closures chapter. Use as an argument to other functions: setTimeout(function() { alert('hello'); }, 1000);


1 Answers

I am going to go against the flow a little here and make the case that anonymous functions are indeed bad practice even though they are widely used.

1) Anonymous functions cannot be reused.

2) Anonymous functions, by definition, do not have a name and so do not describe what they do. Which is to say the code is not self documenting.

3) Anonymous functions cannot be tested in isolation with a unit testing framework.

4) I personally think they make code more difficult to read and debug. Though your experience may vary.

I do think there are situations where an anonymous function is the best choice and as a general rule in order to avoid the above downsides I almost always name my functions.

Typically the longer your anonymous function becomes the more likely that it would benefit from having a name.

like image 83
bhspencer Avatar answered Oct 01 '22 18:10

bhspencer