A few people have asked me how to improve their JavaScript ability. Not just learn about syntax and crazy stuff like closures, but how to apply the same design skills they have in their primary language(s) to the code they stuff into .js files.
I think the key is to submerse yourself in JavaScript for an extended period of time. So often in web development we context-switch into JavaScript mode to bang out a few client-side event handlers, then jump right back into the server code. I’m not suggesting you try to write all the JavaScript code for a web site all at once (that’s just silly), but you could try a code kata with JavaScript every now and then.
Uncle Bob has a nice bowling game Kata. It’s written in Java, however, you can play along with any other language, including JavaScript.
Here’s how to start (for ASP.NET developers):
1. In Visual Studio, select File –> New –> Web Site.
2. Delete the Default.aspx file.
3. Download jQuery and qUnit (both qUnit.js and qUnit.css). Add them all to the root of the site.
4. Add a new HTML page to the web site with the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link href="qunit.css" rel="stylesheet" type="text/css" /> <script src="jquery-1.3.2.min.js" type="text/javascript"></script> <script src="qunit.js" type="text/javascript"></script> <script> </script> </head> <body> <h1 id="qunit-header">JavaScript Code Kata</h1> <h2 id="qunit-banner"></h2> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> </body> </html>
5. Start practicing.
As an example, here is what you might have inside the script tags by slide 18 on Uncle Bob’s Bowling kata:
test("Test Gutter Game", function() { var game = new Game(); for (var i = 0; i < 20; i++) { game.roll(0); } equals(0, game.score()); });
And by slide 19 you’ll make the above test pass. You might have the following code (inside the script tag, or you could put it in a separate .js file).
function Game() { } Game.prototype = { roll: function(pins) { }, score: function() { return 0; } };
Once you get to the end, try some other katas. Or, try the same kata with a different style (like avoid for loops, as an example). Everything gets easier with practice.
JavaScript submersion is fun (and makes you better too).