Posts

Showing posts with the label jsstyle

Brace styles and JavaScript

In languages whose syntax is derived from C (e.g.: C ← C++ ← Java ← JavaScript), two brace styles are most common: Allman style and 1TBS. Allman style If a statement [1] contains a block, that block is considered as somewhat separate from the header of the statement: its opening brace is in a line of its own, at the same indentation level as the head. For example: function foo(x, y, z) { if (x) { a(); } else { b(); c(); } } 1TBS (One True Brace Style) Here, a block is more closely associated with the header of its statement, it starts after it, in the same line. For example: function foo(x, y, z) { if (x) { a(); } else { b(); c(); } } 1TBS is a variant of the (older) K&R (Kernighan and Ritchie) style. In K&R style, functions are written in Allman style and braces are omitted where they are not necessary, e.g. around single-stateme...

Variable declarations: three rules you can break

This blog post mentions three rules that are commonly given for using var statements. And then tells you when you can break them. To make things easier to understand, I somewhat disparagingly call the rules “conventional wisdom” and breaking the rules “unconventional wisdom”. But I will also explain why the rules have been created in the first place. For this blog post, you should know how JavaScript’s function-scoped var declarations work. Consult [1] if you don’t. Three rules you can break Rule to break: Don’t put a var statement inside a block Conventional wisdom in JavaScript tells you that the following code is bad: // Unconventional wisdom function foo(x, y) { if (x > y) { var tmp = x; x = y; y = tmp; } ... } Point: Looking at the code, one might think that the variable tmp only existed inside the then-block of the if statement. What really happens is that the variable declaration is hoisted – the d...