Why use parenthesis on JavaScript return statements?
There are two things about JavaScript’s return
which are a little unintuitive:
A
return
statement followed by unreachable code is perfectly validfunction doSomething() { return // Valid, but will never be called doSomethingElse() }
JavaScript will automatically insert a semicolon at the first possible opportunity on a line after a
return
statement
// JavaScript inserts a semicolon after the `return` statement!
return; // <--- wrong!
React.createElement('li', {className: 'Contact'},
React.createElement('h2', {className: 'Contact-name'}, this.props.name)
)
So, back to the original question: why use brackets on areturn
statement?
Well, if you place your opening bracket on the same line as return
:
return (
No semicolon can be automatically inserted until that bracket is closed.
return (
...
) // <-- JavaScript inserts semicolon here
Of course, we could just place the React.createElement
on the same line as return
, and avoid these superfluous brackets. But then it wouldn’t look as pretty.
tl;dr
If possible, JavaScript will automatically insert a semicolon at the end of the line which the return
statement is on. Use brackets to make it impossible.