JS library best practice: return undefined or introduce error when entering the wrong function?

When coding a library in JavaScript, what is the most standard (friendly?) Way to handle invalid function input? My gut tells me that returning undefined is fine, but is it really useful to make a mistake instead? Or does it really not matter?

I could also see a return of false, null, or even -1, but I don't think they will be as widely expected.

(If this question is too subjective, I'm glad to make it cw.)

+4
source share
3 answers

Benefits of exceptions:

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

Disadvantages of exceptions:

  • Catching an exception is much slower than checking the return value, so if the error is common, then the exceptions will be much slower.
  • If the calling code will check for errors on every API call they make (and not catch exceptions at a higher level), exceptions are more worrying to write around every API call than just checking the return value.
+1
source

I think undefined fine, but keep in mind that:

JavaScript is not of type void, so every function should return a value. The default value is undefined, with the exception of constructors, where this is the return value by default.

Therefore, you do not need to explicitly return undefined. It will be the default.

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

+4
source

possibly obvious. If you expand your environment, continue your practice at least.

Quick response . If it is javascript in the browser undefined OK, if it is javascript on the server, output an error.

Improvement. Let the library user select the behavior as a parameter, either a global library or an object-based object.

0
source

Source: https://habr.com/ru/post/1388745/


All Articles