Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript braces on new line or not? [closed]

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.

like image 636
Tower Avatar asked Jul 10 '10 10:07

Tower


People also ask

Are braces necessary in one line statements in JavaScript?

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.

What is the purpose of {} squiggly braces in Java?

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.

Do you need curly brackets in JavaScript?

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.

Can you use brackets in JavaScript?

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.


1 Answers

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's return 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.

like image 139
Daniel Vassallo Avatar answered Oct 29 '22 17:10

Daniel Vassallo