Pouring over the release notes regarding jQuery 1.4, I came acrosss $.noop()
which is:
Description: An empty function. (added in 1.4)
You can use this empty function when you wish to pass around a function that will do nothing.
Perhaps I'm missing something profound here, but what exactly is a practical use of passing around an empty function?
Code examples appreciated.
I use a couple of plugins which require callbacks, but for some parts I don't actually want to use a certain callback. So, I put in function() {}.
noop is defined in the jQuery source as
so it will fit anywhere you'd use a blank function, such as the above example.
If a function requires you pass a function as an argument maybe? It's shorter to say
do_something($.noop)
thando_something(function(){})
.Although not by much...
...6 characters...
...yeah, that feature looks quite useless actually.
It's purely a convenience/replacement for
function(){}
in the context of where callbacks are required - I don't think I'll be using it anytime soon.I bet the jQuery team had quite a laugh when they dropped it in though, also serves a comedic purpose.
It can be useful if you have a function that supplies functions to other functions.
Example: You have a List of data. Each item has a Button that does something. The "something" can be different for every item. You have a "FunctionFactory" that takes in the item and returns a function. If you don't want the button to do something for whatever reason, then the cleanest way could be to return an empty function, as that way you know that your Factory ALWAYS returns a function.
I don't have a concrete example for jQuery, but I guess this could come in handy when used in an .each or .map block.
Probably if some bad API requires a function as a parameter, and you don't want to do anything in it, this would be a framework-supported way of making that obvious.
This function was proposed due to performance issues on embedded systems when using
$.ajax
, reported on the jQuery-Dev mailing list. You can see the thread.Basically, they preferred to introduce and use this single empty function, rather than declaring empty anonymous functions all around.
Now this function is internally used in the ajax, event and offset modules.
You can give a look to the commit when it was introduced also.