![]() |
World's largest bowl of spaghetti ... or how I wrote JavaScript the first half of my career |
A lot of this will seem like common sense to some, but I have on many occasions seen very good developers write some pretty poorly structured JavaScript apps (including myself, haha), and I've been asked about it a few times recently, so I'll give it a shot. I hope to go over most of what I know in this arena. There is a good amount to go over, but I'll try to hit the most important basics.
Use A JavaScript Bundler/Minifier/"Compiler"
Use the Module Pattern
So basically you're looking at something like this:
;var myModule = (function($, foo) { //here $ and foo are local to the scope. //here's some private variable. var bar = 123; //here's a private function function superThing() { alert('Bar is ' + bar++); } /** You can alter injected objects to effect the outside **/ // here we'll alter the jQuery object by adding a plugin. $.fn.superPlugin = function() { $(this).on('click', superThing); }; // same as above but we're removing a binding here. $.fn.removeSuperPlugin = function() { $(this).off('click', superThing); } /** You can have it return an interface to whatever it's doing **/ return { incrementBar: function () { bar++; }, callSuperThing: function (){ superThing(); } }; })(jQuery, foo);
Note: So what's the ; for in the module above? Basically to keep bundlers and minifiers from combining two function calls into one function call, causing errors:
(function(a,b){})(c,d)(function(w,x){})(y,z)
Structure Your Files Appropriately
An example of such a file structure might be (for an Angular app for example):
+-App | +-Directives | | +-my-click-directive.js | | +-table-directive.js | | +-directives-module.js | | | +-Controllers | | +-HomeCtrl.js | | +-SearchCtrl.js | | +-FooCtrl.js | | | +-Services | | +-facebook.js | | +-twitterSearch.js
... you get the idea. But the point is that in the end, it doesn't matter how many files you have, as long as you can easily maintain and organize them. The alternative is to have the one JavaScript "mega-file" which I've seen way too many times.
But, How Do I Debug Bundled Or Minified Files?
But what about if the file is minified? Well, now you're in for it, I guess. However, some browsers, such as Google's Chrome actually have a feature to "prettify" minified code to so you can step through it in a readable format. (In Chrome this feature is a little button with a {} in it in your developer's console)
LOOK AT OTHERS' EXAMPLES!!!
Another really great way to get an idea on how to structure your JavaScript code is too look at examples presented by others. They are all over the place these days! Just think of your favorite JavaScript framework or library and check them out on GitHub: JQuery, Angular, Ember, etc. All really awesome examples of how to effectively structure your JavaScript code and files.