Saturday, January 21, 2012

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.
http://en.wikipedia.org/wiki/Indent_style
After rereading some bits about coding style from Douglas Crockford's Javascript: The Good Parts.

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...
var test=function(){
    if (1 === 2)
        alert("I never fire");
        alert("I always fire");
};

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 ...
var test=function(){
    if (1 === 2){
        alert("I never fire");
    }
    alert("I always fire");
};
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.
var test = function(){
    if(1!==2){
        alert("I will fire");
        alert("I will also fire");
    }
}

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.




2 comments:

rugg said...

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
http://www.jslint.com

Terrance Smith said...

@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.