Brace for style. Why brace style matters in javascript.

In most c like languages bracket “{” location is a matter of personal tastes.

Like so many other thing.. its a different story for javascript.
After rereading some bits about coding style from Douglas Crockford’s Javascript: The Good Parts. <a href=””> Widgets</a>

I came across a blurb that could potentially cause some pain in developers wanting to use a different style of bracing such as the following…

In this case the second alert box will fire regardless of the conditional statement outcome.This is due to “slightly off” javascript parsing behavior. What the interpreter actually will run is the following …

Your best bet is to use braces. For the most part 1TBS or K&R style seem to be the most common I’ve seen. In particular 1TBS is used in the jQuery library.

As with much of programming you really want to try things for yourself instead of taking them at face value.
So try it yourself in the fiddle down here.

  • You know I’m anal retentive about my code. I believe that for any c style language you should ALWAYS explicitly brace your code. I’ve even been known to put #begina and #end around my python methods.
    Oh and this has saved me tons of headaches

  • @rugg Yes, I am ever so thankful for jsLint. It does help out a lot. I will say I do leave out the bracket in my C# & Java code and I do like using ternary operators instead of writing out conditional statements where possible in big, hierarchal, deep and heavy stuff. Alas I am guilty there but, if I didn’t know javascript’s quirkiness and jsint I’d have been tempted.