Why use parentheses when returning in JavaScript?

Viewed 17597

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?

9 Answers

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

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

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.

Related