What is the JavaScript convention for no operation?

前端 未结 6 1825
执念已碎
执念已碎 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 18:43

    There is absolutely no problem or performance penalty of using Function.prototype over () => {}.

    The main benefit of Function.prototype is having a singleton function rather than re-defining a new anonymous function each time. It's especially important to use a no-op like Function.prototype when defining default values and memoizing as it gives you a consistent object pointer which never changes.

    The reason I'm recommending Function.prototype rather than Function is because of they're not the same:

    Function() === Function()
    // false
    
    Function.prototype() === Function.prototype()
    // true
    

    Also, benchmarks from other answers are misleading. In fact, Function.prototype performs faster than () => {} depending on how you write and run the benchmark:

    You can’t trust JS benchmarks << Specifically calling out benchmarks on this question.

    Don't style your code from benchmarks; do whatever's maintainable and let the interpreter figure out how to optimize in the long run.

提交回复
热议问题