Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use parentheses when returning in JavaScript?

Tags:

javascript

In the Restify framework code I found this function:

function queryParser(options) {      function parseQueryString(req, res, next) {         // Some code goes there         return (next());     }     return (parseQueryString); } 

Why would the author write return (next()); and return (parseQueryString);? Does it need parentheses there and if so, why?

like image 753
silent_coder Avatar asked Dec 29 '13 11:12

silent_coder


Video Answer


2 Answers

Using parentheses when returning is necessary if you want to write your return statement over several lines.

React.js offers a useful example. In the return statement of the render property in a component you usually want to spread the JSX you return over several lines for readability reasons, e.g.:

render: function() {     return (         <div className="foo">             <h1>Headline</h1>             <MyComponent data={this.state.data} />         </div>     ); } 

Without parentheses it results in an error!


More generally, not using parentheses when spreading a return statement over several lines will result in an error. The following example will execute properly:

var foo = function() {    var x = 3;    return (      x       +       1    );  };  console.log(foo());

Whereas the following (without the parentheses) will throw errors:

var foo = function() {    var x = 3;    return       x       +       1    ;  };  console.log(foo());
like image 97
Andru Avatar answered Oct 12 '22 11:10

Andru


It doesn't need to be that way, but it's valid JavaScript code. Actually it's quite uncommon to see such syntax. I guess it's a personal preference of the author.

like image 35
Darin Dimitrov Avatar answered Oct 12 '22 11:10

Darin Dimitrov