What is the JavaScript convention for no operation?

前端 未结 6 1817
执念已碎
执念已碎 2020-11-30 18:00

What is the JavaScript convention for no operation? Like a Python pass command.

  • One option is simply an empty function: function() {}
6条回答
  •  情歌与酒
    2020-11-30 19:00

    I think jQuery noop() is mostly intended to prevent code from crashing by providing a default function when the requested one is not available. For example, considering the following code sample, $.noop is chosen if fakeFunction is not defined, preventing the next call to fn from crashing:

    var fn = fakeFunction || $.noop;
    fn() // no crash
    

    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. Use null, false or 0 if you like, in your case there will be no side effect. Furthermore, it's worth noting that this code...

    true/false ? alert('boo') : function(){};
    

    ... is completely useless since you'll never call the function, and this one...

    true/false ? alert('boo') : $.noop();
    

    ... is even more useless since you call an empty function, which is exactly the same as...

    true/false ? alert('boo') : undefined;
    

    Let's replace the ternary expression with an if statement to see how much it's useless:

    if (true/false) {
        alert('boo');
    } else {
        $.noop(); // returns undefined which goes nowhere
    }
    

    You could simply write:

    if (true/false) alert('boo');
    

    Or even shorter:

    true/false && alert('boo');
    

    To finally answer your question, I guess a "conventional no operation" is the one which is never written.

提交回复
热议问题