How long should a JavaScript function be?
October 23rd, 2010Writing code the right way is hard to do. To begin with, what’s the right way anyway?
And, what’s a good length for a JavaScript function?
I’d say 5 to 10 lines at maximum. Preferably even shorter than that. JavaScript just wants you to do functional programming. Write lots of functions.
Short functions have lots of advantages:
- Atomic functionality: they do exactly one thing
- Easier to understand when you come back later
- Ideal for unit testing
- Debugging tends to be simpler
- Refactoring is a snap
- Well-suited for closure-pattern APIs
- Chances for code reuse increase
There are two main disadvantages:
- Longer code (all the
function(){}
blocks) - A tiny bit slower (lots of function calls)*
Both of these are in almost any case not an issue because good minification and gzipping takes care of code size and can even inline function calls.
Here’s an example where I’ve used really short functions, it’s from my creditcard_js validation library:
var CreditCard = { // …more stuff… validate: function(number){ return CreditCard.verifyLuhn10(number) && !!CreditCard.type(number) && !CreditCard.isTestNumber(number); }, verifyLuhn10: function(number){ return ($A(CreditCard.strip(number)).reverse().inject(0,function(a,n,index){ return a + $A((parseInt(n) * [1,2][index%2]).toString()) .inject(0, function(b,o){ return b + parseInt(o) }) }) % 10 == 0); }, isTestNumber: function(number){ return CreditCard.TEST_NUMBERS.include(CreditCard.strip(number)); }, strip: function(number) { return number.gsub(/s/,''); }, type: function(number) { for(card in CreditCard.CARDS) if(CreditCard['is'+card](number)) return card; } };
Note that many of those functions actually start with return
and try to be really concise (if you don’t understand the verifyLuhn10
function, don’t worry!).
At the end of the day, this scientific chart is a good guideline to how many lines of code a function in JavaScript should have:
*Yes it’s slower, academically speaking. But only a tiny weenie little bit. There’s no way this unnoticeable performance loss is going to outweigh the advantages. Just trust me on this, don’t ever prematurely optimize for performance. Save yourself the trouble, and you’ll live happier.
Of course there are no magicals unicorns and no silver bullets for anything in programming. Sometimes, just sometimes you will actually hit a performance issue that requires you to get rid of all your nice little tiny functions and rewrite it to be really long with lots of lines of code. Stick a “it depends” post-it note to your monitor. It really does.
Tweet