JS library best practice: Return undefined or throw error on bad function input?

前端 未结 3 1093
粉色の甜心
粉色の甜心 2021-01-03 02:24

When coding a library in JavaScript, what is the most standard (friendliest?) way to handle invalid input to a function? My gut tells me that returning undefined is perfectl

相关标签:
3条回答
  • 2021-01-03 02:43

    Advantages of exceptions:

    • If an error is a rare occurrence (not expected in normal operation), then it may be easier and faster for the calling code to catch exceptions in one higher-level place rather than test return values after every API call.

    Disadvantages of exceptions:

    • Catching an exception is a lot slower than testing a return value so if an error is a common occurrence, then exceptions will be a lot slower.
    • If the calling code is going to check errors on every API call they make (and not catch exceptions at a higher level), exceptions are more of a pain to write around every single API call than just testing a return value.
    0 讨论(0)
  • 2021-01-03 02:54

    maybe obvious If you extending an environment - continue their practice as a minimum

    Quick answer. If this is javascript in the browser undefined is OK, if it is javascript in the server throw an error.

    Improved Let the library user select the behavior as an option, either library global, or on an object by object basis.

    0 讨论(0)
  • 2021-01-03 02:55

    I think undefined is fine but keep in mind that:

    JavaScript does not have a void type, so every function must return a value. The default value is undefined, except for constructors, where the default return value is this.

    So you don't need to explicitly returns undefined. It will be by default.

    see http://javascript.crockford.com/survey.html

    0 讨论(0)
提交回复
热议问题