Javascript code review

I’m new to Javascript hackery, my little aviation weather hack had me doing a lot of new stuff with Ajax and dynamic HTML. So I asked my friend Mike for a code review. He’s the smartest Javascript hacker I know, and we both worked at Google where rigorous code reviews were a thing.

Here’s some complicated things I learned from him:

  1. There’s ways to create private namespaces for libraries and classes. Douglas Crockford’s “Private Members in JavaScript” is a good introduction, some examples from Mike are kmeans.js and crimespotting.js. The key thing is creating a closure to scope the private stuff, then assigning the public functions to a module object. There’s potential per-instance overhead to doing it this way.
  2. Reassigning the CSS class of a DOM element at runtime is totally OK. In jQuery, it’s like doing foo.attr("class", "someStyle"). It’s a handy way to make the document suddenly look different, but it made me nervous.
  3. Editing the CSS style of a DOM element is also OK. In jQuery, it’s doing foo.css("font-weight", "bold"). Presumably it’s using to do the manipulation.
  4. jQuery.ajax() gives different types types depending on what it thinks the response is. XML gives back a DOM object, HTML gives back a string, JSON gives back a Javascript blob. My code is getting HTML and then uses the magic jQuery(htmlString) capability to parse the HTML into a DOM and then query it. (BTW, turning strings into DOM is not easy in Javascript.)

Also some simple things:

  1. Javascript has Array.join() just like Python. Handy to avoid lots of String concatenation.
  2. Not clear that testing if (foo === 3) is worth typing the extra =. There’s circumstances where it saves you, but in practice may not be a big deal.
  3. Array.push() can take multiple arguments, to avoid repeated calls
  4. return "" + x is an easy way to ensure the return type is always a string
  5. Be sure to use “var” for all local variables. This is rookie Javascript, but I still forget.

I learned a lot. Code reviews are a great way to teach and learn, it’d be nice to have an online community that offered them along the lines of StackOverflow or github. Both for basic education, but also helping clean up important open source libraries. Key tech piece: a really good browser based code annotation tool.

Now as a favour in kind I’m going to try porting my code from using jQuery to using his D3 library. D3 is more of a visualization library than a jQuery replacement, but it happens to have the selectors and Ajax support I need.