Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 perfectly fine, but is it actually more helpful to throw an error instead? Or does it really not matter?

I could also see returning false, null or even -1, but I don't think those would be as widely expected.

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

like image 209
Thomas Avatar asked Dec 31 '11 17:12

Thomas


1 Answers

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

like image 142
plus- Avatar answered Sep 27 '22 18:09

plus-