At work, we place braces on the next line, but at home, I do the opposite. Which one do you prefer? (K&R vs OTBS)
function something() { // ... } function something() { // ... }
A lot of JavaScript libraries seem to use the OTBS (one true brace style). I'd like to follow them for consistence among other JavaScript projects, but doesn't K&R style look more readable?
Note: We know the problem with return and braces in JavaScript, that will always be an exception. However, that is only a single case.
No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
To edit JavaScript code, you can use the same techniques that you use to edit HTML or CSS. However, a JavaScript file must have the . js extension. By default, when you type the left brace, left parenthesis, or left quotation mark in a JavaScript statement, Brackets adds the right brace, parenthesis, or quotation mark.
Douglas Crockford gives a reason for choosing the K&R style1:
I always use the K&R style, putting the
{
at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript'sreturn
statement.
The blunder he is referring to is how JavaScript handles the return
statement differently in the following two scenarios:
return { 'status': 'ok' };
... and:
return { 'status': 'ok' };
The first one will return an object with a status
property, while the latter will return undefined
because of semicolon insertion.
1Douglas Crockford: JavaScript: The Good Parts: Style (page 96) - ISBN: 978-0596517748.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With