1

I found this code in one a tutorial.

const renderApp = (Component) =>
  render(
    <Provider store={store}>
        <AppContainer>
          <Component />
        </AppContainer>
    </Provider>,
    document.getElementById('root')
  );

My question is shouldnt the return value be wrapped in braces? because arrow functions return whats next to => if nothing is metnioned ?

const renderApp = (Component) => (
  render(
    <Provider store={store}>
        <AppContainer>
          <Component />
        </AppContainer>
    </Provider>,
    document.getElementById('root')
  );
)

shouldn't it have braces to wrap contents ?

  • The reason it's not wrapped in () is because it's a one-liner :) – Tempuslight Feb 17 '22 at 09:42
  • 1
    No, you only need round parentheses when you're returning an anonymous object `val => ({ prop: val });`. – Cristian Feb 17 '22 at 09:44
  • Im still not getting it. The first code snippet, after "=>" its empty, wont JS compiler insert ; and end it there ? why will it return render functions output ? Thanks –  Feb 17 '22 at 09:45
  • 1
    @vikasr78 - *"wont JS compiler insert ; and end it there"* No. It would with a `return` statement, but not with an arrow function's `=>`. They're fundamentally different things. – T.J. Crowder Feb 17 '22 at 09:46
  • You mind find [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283/218196) interesting. – Felix Kling Feb 17 '22 at 09:48

2 Answers2

3

The right hand side of an arrow function can be either:

  • A block
    • delimited with { and } (which are braces)
    • which returns whatever the return statement in the block says
  • An expression
    • which returns whatever the result of evaluating the expression is

You need to wrap the expression with parenthesis (( and )) if it is an object literal because object literals are delimited with braces.

() => { foo: 123, bar: 456 }; // This is an error

If you wrote the above, the { and } would be interpreted as a block and not an expression to create an object.

() => ({ foo: 123, bar: 456 });

Adding parenthesis tells the JS parser that it is an expression and not a block.

Since your expression doesn't start with a {, it won't be treated as a block so there is no need for parenthesis.


The first code snippet, after "=>" its empty, wont JS compiler insert ; and end it there ?

No. Automatic semi-colon insertion only occurs in places which could be the end of something. It won't happen in after => because there must be something on the right-hand side of =>.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

There's no need to wrap it within braces because a single line statement gets returned implicitly. You however can do it yourself, it isn't incorrect, just that it's a bit of syntactic sugar

Ammar
  • 106
  • 5