atroche.org

My name's Alistair Roche. Follow me on Twitter here.

Sep 6

JavaScript Indentation

JavaScript doesn’t have a PEP8 equivalent. There’s no official rule about how code should be indented. Community styleguides (of which there are many) have no clear consensus. What’s a coder to do?

I wrote a script to clone the 100 most watched JS projects on GitHub1 and determine the type of whitespace they use for indenting their .js files. Here’s a summary:

Indentation used in top 100 watched JS GitHub projects

Compare this to the universal dominance of particular styles in other languages like Ruby and Python, and it seems bizarrely egalitarian. Is the JS community particularly fractious and disorganised?

The top ten projects tell a different story. Eight of them use two spaces (jQuery and three.js both use tabs.)

How do the results compare with advice from the most prominent styleguides?

jQuery is used by more than half of all websites, and Douglas Crockford wrote Stack Overflow’s favourite JavaScript book, but it’s clear that they’re both out of touch with the JavaScript community.

The prevalence of the two spaces style is probably a result of the influence of the Ruby and Rails on web development, and of the callback-driven nature of browser / Node.js development. But I’d love to hear other suggestions as to why.2

For my next trick I’ll adapt my code (written in CoffeeScript, by the way) to investigate line length, trailing whitespace and other questions of JavaScript formatting. If you want to see where it goes, follow me on Twitter here.

Indentation is a matter of personal preference (it’s why they call it style, after all), but if you’re starting an open source project and want it to be consistent with community standards, indent with two spaces.

Join the discussion on Hacker News


  1. Projects on GitHub might not reflect how most programmers (who work on commerical software) are writing their code. But seeing as most production JS is minified beyond recognition, it’s the best dataset we’ve got to work with. 

  2. My friend and mentor Tim Diggins suggested investigating the influence that the server-side language has on JavaScript style. I’d guess that, e.g., projects using Python on the backend tend to use four spaces. 


  1. drpizza reblogged this from atroche
  2. postpostmortem reblogged this from atroche
  3. atroche posted this