60

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?

3
  • 2
    It is not required. It's just a choice. Commented Dec 29, 2013 at 11:16
  • 1
    It might also being used to avoid automatic semicolon insertion. Commented Dec 29, 2015 at 21:44
  • 3
    Interesting post here on the topic jamesknelson.com/javascript-return-parenthesis thanks for the great question helped me learned a bunch Commented May 11, 2018 at 12:41

10 Answers 10

139

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());

Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer. Return doesn't allow statements over multiple lines natively
@Callat Sure it does allow multi-line expressions. You just must not put a linebreak right after the return, otherwise the expression becomes its own statement - but that's all.
22

Parenthesis are used for two purposes in a return statement.

  • To support multi-line expression as mentioned in @Andru Answer.
  • To allow returning object in arrow function like the below:

() => ({ name: 'Amanda' }) // Shorthand to return an object

This is equivalent to

() => {
 return { name : 'Amanda' }
}

For more information, please check this article. https://medium.com/@leannezhang/curly-braces-versus-parenthesis-in-reactjs-4d3ffd33128f

3 Comments

Great focus on the arrow function detail!
It is important to note that in () => ({ name: 'Amanda' }) the use of parenthesis is not a shortcut: the code inside curly braces is parsed as a sequence of statements
Is it allowed to use parenthesis inside curly braces wrt arrow function or either of them needs to be used ?
18

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.

4 Comments

@silent_coder In this specific case it's nothing for. Usually you can see parentheses used to enclose visually hard understandable parts of code, i.e. while using complex ternary operators. In the code above the parentheses could be even misleading for inexperienced developers, cause return in that case looks more like a function call.
Call me inexperienced developer but for a moment these parentheses caused confusion and I did a little search to figure it out as it looked exactly like a function call :)
This is usually syntax being carried over from C++14 where it does have an impact or from old school programmers from the era when C was the popular language of its time; it was just a convention for some coders.
Never use parentheses for unary operators such as delete, typeof and void or after keywords such as return, throw as well as others (case, in or new). google.github.io/styleguide/javascriptguide.xml
8
// Create a component named MessageComponent
var MessageComponent = React.createClass({
  render: function() {
    return (
      <div>{this.props.message}</div>
    );
  }
});

NOTE Why do we need the parentheses around the return statement (line 3)? This is because of JavaScript's automatic semicolon insertion. Without the parentheses, JavaScript would ignore the following lines and return without a value. If the JSX starts on the same line as the return, then parentheses are not needed.

Taken from here.

Comments

2

Just to add to what others have said.

Using brackets around the return value is valid JavaScript, but mostly a bad thing to do.

Mostly bad because it doesn't add anything yet increases the size of the JavaScript which means that there is more to download to the browser. Yes most people have fast broadband connections, but don't lose sight of the fact that everything you put in the JavaScript file needs to be downloaded so avoid unnecessary code bloat. This probably doesn't matter if you use a tool to compact your code (minifier has already been mentioned), but not everyone does.

Sometimes it might aid readability. Hard pressed to think of an example in this case, but if the use of brackets makes your JavaScript clearer to you as the developer and thus easier to maintain then use them - even if it goes against what I said about code bloat.

Comments

2

Why would the author write return (next()); ... ?

Regarding next():

Probably because his function is something like this:

function next()
{
  var i=0;
  return function (){
    // Do something with that closured i....
  }
}

Regarding (xxx);:

It is unnecessary. Every minifier will remove it.

Example (uglifyJS):

Enter image description here

becomes:

Enter image description here

Comments

1

I tried:

var a = function() {
          return true || true
        }
console.log(a());

//return: true
var a = function() {
          return
              true || true
        }
console.log(a());

//return: undefined
var a = function() {
          return (
                   true || true
                 )
        }
console.log(a());

//return: true

Comments

0

While Andru's answer is popular, it is wrong that parantheses are required for multiline return statement. Here, you can see an object of foo and bar is returned with no parantheses needed.

function foo () {
  return {
    foo: 'foo',
    bar: 'bar',
  }
}
console.log(foo())

As long as the return line is not just empty space or linebreak, you can have a multiline return just fine. Otherwise Automatic Semicolon Insertion takeover and break your return statement as demonstrated by Andru.

Regarding your question, I am onboard with Darin's answer.

1 Comment

You're describing the special case of returning an object (in your code you also have to write the opening curly bracket in the same line as the return keyword). You are not describing the general case of returning any statement - which needs parentheses in case its spread over several lines.
0

Check this video https://www.youtube.com/watch?v=xw5SJZnTWp4&t=224s

i noticed while trying this code which can help make a function to support currying, notice line 6 where return have wrapped in (), without parentheses this code does not have capability to return a invokeable function,

so what i feel like return () return a response in a pattern which can support IIFE when response is invoked with ()

similary method returned on line no. 6 wheather it return targetFunction or further curry(), that returns a response with a pattern which can support response to be invoked with ()

hope I am able to explain :)

const addUncurried = (a, b) => a + b;
const curry = 
    (targetFunction, collectedArguments = []) => {
          return (...currentArguments) => {
              return (allArguments => {
                return (
                    allArguments.length >= targetFunction.length 
                    ? targetFunction(...allArguments) 
                    : curry(targetFunction, allArguments)
                )
              })([
                ...collectedArguments,
                ...currentArguments,
            ])
          }
    }
        
   
const addCurried = curry(addUncurried);
const increment = addCurried(2); // 6
console.log('increment',increment(4));
console.log('addCurried',addCurried(1,4)); // 5 
console.log('addCurried',addCurried(1)(3)); // 4

Comments

-2

This may be old but the return () can be used in this way:

function parseQueryString(req, res, next) {
            var id = req.param('id');
            return (id ? "Foo" : "Bar");
}

Less code, easy to read :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.