Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

Why use parentheses when returning in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...