For those who develop applications using C# or Javascript, but I think Java too, (I’m not a Java developer and then I don’t know if what I’m going to say is true for them as well) , there are two kind of writing styles for indentation and code’s blocks formatting .
These styles, known as K&R (Kernighan & Ritchie) style and Allman style, concern the way the opening curly brace is opened, when defining a block of code.
The former places the brace in the same line as the preceding line of code, as you can see in this example:
return { name: "Joe" };
the latter places the curly brace in its own line, as shown here:
return { name: "Joe" };
So, the question is:
Can I use both of these styles or not when writing code ?
The answer is: yes, except for Javascript code.
In Javascript you must always use the K&R style if you want to avoid some subtle bugs that may be very difficult to identify.
For example, if you used the code in Allman style showed below
the return value would be “undefined” and not an object as expected, because the browser insert a semicolon after the word “return”.
If the code below had written in K&R (Kernighan & Ritchie) style:
as shown in first example, the return value would have been an object as expected.
528 thoughts on “Javascript code block formatting”
Comments are closed.