Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What real purpose does $.noop() serve in jQuery 1.4?

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.

like image 810
Sampson Avatar asked Jan 15 '10 03:01

Sampson


People also ask

What is Noop in jQuery?

The noop() function is an empty function in jQuery. It does not accept any parameter. We can use this function when we have to pass around a function that does nothing. This method returns undefined. Instead of declaring multiple anonymous functions, we can use the noop() function as a single empty function.

Why use noop function?

Then, noop() allows to save memory by avoiding to write the same empty function multiple times everywhere in your code. By the way, $. noop is a bit shorter than function(){} (6 bytes saved per token). So, there is no relationship between your code and the empty function pattern.

What is Noop in JavaScript?

A "noop" (no-op, or NOP) is a "no-operation" function, which does nothing. We can create a noop function in JavaScript in the following ways: function noop() {} const noop = function () {}; // or, ES6+ equivalent const noop = () => {}; Hope you found this post useful.

Do nothing in jQuery?

JQuery | noop() method This noop() Method in jQuery is the empty function when user wishes to pass around a function that will do nothing. Parameters: The noop() method does not accept any parameter. Return Value: It returns the undefined.


2 Answers

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.

like image 168
Christian C. Salvadó Avatar answered Sep 29 '22 15:09

Christian C. Salvadó


If you have a function that accepts a function as a parameter, and you don't have any code to give it, you can pass $.noop.

I can't think of any such cases in jQuery where the parameter isn't optional in the first place, though.

Unlike writing function(){}, passing $.noop will not create a new function instance, saving a bit of memory. However, if whatever you're passing it to modifies the function object (eg, funcParam.id = 2), passing $.noop will mess things up.

like image 42
SLaks Avatar answered Sep 29 '22 15:09

SLaks