jQuery API

jQuery.noop()

jQuery.noop() Returns: Function

Description: An empty function.

  • version added: 1.4jQuery.noop()

You can use this empty function when you wish to pass around a function that will do nothing.

This is useful for plugin authors who offer optional callbacks; in the case that no callback is given, something like jQuery.noop could execute.

Support and Contributions

Need help with jQuery.noop() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.noop()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/sethaldridge Seth

    Is this like the Seinfeld of functions? A function about nothing.

  • JustAJoke

    I Guess is for compatibility with NaDa

    http://www.bernardbelanger.com/computing/NaDa/index.php

  • http://twitter.com/puffpio David Pio

    I think it is used for functions that require a callback as a parameter..but you don’t want to do anything in a callback..rather than creating empty functions all the time..do this..

  • Anonymous

    It’s like Prototype.K shorthand for function(){}it can be useful for validating callbacks such as:function myFunc(num, callback){ var x = num * 100; # run callback if provided (callback || $.noop)( x ); return x;}

    • Dcodex

      function myFunc(num, callback){

      var x = num * 100;

      # run callback if provided
      (callback || $.noop)( x );

      return typeof callback != ‘undefined’ ? callback(x) : x;
      }

  • http://www.facebook.com/marcorogers Marco Rogers

    It's not overly useful. But typing $.noop is 6 chars shorter than function(){}. Also if you use this everywhere instead of creating new, anonymous, empty functions, you'll slightly cut down on memory.

    • AreN

      That’s a good point when it comes to performance

    • CrGeary

      what about if you were to have this:

      var z = $.noop();

      then whenever you need to use $.noop();, you only have to type: z

      That would make it smaller right? Ofcourse, only if your using $.noop(); more than once.

      • Jason ‘Zeus’ Brown

        You’re missing the point. $.noop() returns undefined, because it has no return value, so that’s the same as
        var z = undefined;
        The usefulness of $.noop is that it’s an empty function. So pass it where you need a function, but don’t need it to do anything, such as a callback that you’re not making use of. You’re not meant to call it directly, and assign its return value to anything, that has no purpose. If you need to use undefined as a value for something, assign it directly rather than wasting processor ticks on a function call.
        So,
        var z = $.noop;
        would make some sense and
        var z = $.noop();
        is pointless.

  • http://www.learningjquery.com/ Karl Swedberg

    $.noop returns the sound of one hand clapping.

  • http://www.subprint.com joemccann

    Here's where it may be useful, or at least my first usage:


    $('a').bind('click', function(){
    var href = $(this).attr('href');
    // Make bookmarkable.
    !location.hash ? location.href += href : $.noop();
    return false;
    });

    And your html would be an anchor tag where the href was equal to “#foo”.

    • http://twitter.com/xenogenesis xenogenesis

      Are you sure you're not looking for the “if” statement in that excerpt?

      • http://www.subprint.com joemccann

        I prefer to use ternary operators for one line statements. Any time I type “if” I always add the opening and closing curly brace. So to answer your question, no, I'm not looking for the if statement.

        Another way of writing this is:

        !location.hash && (location.href += href);

        Note, no ternary and no if statement. JSLint doesn't like this approach either…

    • http://twitter.com/blahpro Ben Hodgson

      I’m pretty certain that this isn’t the use for which noop was intended — the fact that $.noop() is only one character shorter than undefined (its return value) is a clue.

      • http://www.subprint.com joemccann

        Oh my bad, I didn't know there was a rule book on how to use $.noop().

        Shall we get into the discussion of coding style? Which reads more legibly:

        !location.hash ? location.href += href : $.noop();

        or

        !location.hash ? location.href += href : undefined;

        Also, you'll notice I wrote “Here's where it MAY be useful” not “This is how to use it.”

        • Jamie

          Easier:
          !location.hash ? location.href != href :0;
          or
          !location.hash ? location.href != href :null;
          or
          !location.hash ? location.href != href :false;

          all of these, to me, are easier to read than $.noop();, but ymmv

          • http://www.subprint.com joemccann

            Agreed, namely on ymmv.

          • Draeton

            Or
            !!location.hash && location.href += href;

        • http://twitter.com/The_Mighty_Zeus Jason Brown

          Well, since you asked, undefined or null seems more legible than $.noop(). It exists to be an empty function, there's really no practical value in calling a function that doesn't return anything – just to get its undefined return value.

  • Jamie

    If you are writing any function that requires a callback, $.noop can be useful as a callback stand-in that does nothing, especially for plugin authors or if you're writing a generic function that does calls a callback. Sometimes users of your function may not want to provide a function that actually does anything — they just want to “Fire and Forget.” A good example would be to do an AJAX POST; you might not have anything you need to do if it succeeds — only if there's an error do you need to do anything with the error message. So, you want to provide an empty function as a callback for the success parameter.

    function doMyPost(data, error_callback, success_callback) {

    // using function(){} is just as acceptable as $.noop, but $.noop may be
    // easier to read (maybe)
    success_callback = success_callback || $.noop;

    // maybe the caller doesn't even care about whether an error occurs either
    error_callback = error_callback || $.noop;

    // do something that takes time
    $.ajax(“/some/url”, data, …., {“error”: error_callback, “success”: success_callback…});

    }

    • http://openid-provider.appspot.com/mrdanpsmith bckwld

      Can't you just check and see if the callback option is undefined before attempting to call it in a plugin? That's what I've always done. I'm not understanding this.

      • Markus

        Me either, TBH. A simple typeof check is all you need. BTW, checking to see if it's a function and not undefined might be a better approach.

        if(typeof(callback) == “function”) {
        callback();
        }

        • http://twitter.com/villainous max thom stahl

          How is that a better approach though? There's more code there—and remember you've gotta type all of that stuff any time the callback is ever used.

          • http://openid-provider.appspot.com/mrdanpsmith bckwld

            Writing one if is not a big deal

        • eric

          I guess the real question is which takes less CPU cycles: doing a comparison, branch, and possibly (depending on the result of the comparison) a function call; or simply doing a function call that may or may not do something?

  • idiosyncronaut

    Noop is a very bad idea. Why don't plugin authors just write better plugins? NOP makes sense in low-level languages such as ASM when you need to spend processor clock cycles for strategic purposes. In a higher level language like javascript it is borderline idiotic.

    • http://twitter.com/villainous max thom stahl

      I think you're missing the point…. In assembly language you'd use a NOP instruction where an instruction is required but no action is desired. In Javascript you'd use it the same way: when a plugin has a callback that isn't specified, it should be a function that just returns and does nothing. I agree that it's a little excessive to formalize such a thing by adding it to the jQuery namespace, but it saves you from having to type `function () {return;}`, which is a fine thing for it to do.

      • amcsi

        Also, since it's a reusable empty function, if you do reuse it, you can take advantage of the empty functions being the same object, so comparing them by the == operator results to true (unlike when always defining a new empty function).
        So you can test for an empty function by (fn == $.noop)

  • Flechto

    Am I the only one who wants to use it like this:

    $('.testResult')[youPassed ? 'addClass' : 'noop']('passed');

    Is there a reason it doesn't work like that I should know?

    • Cjg

      That code will work if you run this snipped before it:
      $.fn.noop = $.noop;

      • Flechto

        It need's to be chainable. This is what I did

        $.fn.noop = function () { return this; };

    • http://pulse.yahoo.com/_XVPFTLXQKPJG35K7IQRN4IVNWE Moments

      Same here. $.fn.noop as function() { return this; } would be really nice. I’d like to write something like this:
      $(‘selector’).css({
      style1: ‘value1′,
      style2: ‘value2′,
      }).attr(‘foo’, bar)
      [condition1 ? 'appendTo' : 'noop'](anotherElement)
      [condition2 ? 'addClass' : 'noop'](‘class’);

    • http://twitter.com/monokrome Brandon Stoner

      I think you want:

      $('.testResult')[(typeof youPassed != 'undefined') ? 'addClass' : 'noop']('passed');

  • Kae

    2 cycles ?

  • eric

    I guess the real question is which takes less CPU cycles: doing a comparison, branch, and possibly (depending on the result of the comparison) a function call; or simply doing a function call that may or may not do something?