Of the Programmer Holy Wars, “curly braces on the same line, or the next line?” is not as vitriolic as emacs/vim or tabs/spaces, but it’s up there.

(Personally, I don’t care. I’ve done years with each style. You get used to it.)

In JavaScript, it’s less of an issue, because, when you put curly braces on the next line, JavaScript will (sometimes) automatically insert semicolons into your code. It’s well-documented and discussed, and understandable; here’s a question about it on stackoverflow.

Yesterday I reviewed some old JavaScript (circa 2007) that our web designer Daniel rehabilitated, and this concern came up. Rather than hunt around manually for dangling curly braces, I wrote some ruby to find and fix them.

 1 # fix-js-curies.rb
 2 ARGV.each do |filename|
 3   src = File.read(filename)
 5   # This multi-line regex looks for any { that
 6   # comes after a \n, and any tabs or spaces,
 7   # and replaces it with a space and a {.
 8   new_src = src.gsub(/\n[ \t]*\{/m, ' {')
10   if src == new_src
11     puts filename
12   else
13     puts "#{filename} fixed!"
14     File.open(filename, 'w') do |f|
15       f.puts new_src
16     end
17   end
18 end

You can pass it any .js files as command-line arguments:

1 $ ruby fix-js-curlies.rb app/assets/*.js

Props to Daniel: when I ran my script, it didn’t actually find any, because he got them all ahead of me.