Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow functions and the use of parentheses () or {} or ({})

I cannot understand why in the arrow functions we do not need to wrap the literal of arrow function in the ({}) braces, instead of in this example the literal just wrapped in the single () braces. Why? I had surfed the internet to find an answer on it, but it failed.

And also why we put the arguments in double braces ({}), instead of just ()?

const FilterLink = ({ filter, children }) => (    <NavLink        to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}        activeStyle={ {        textDecoration: 'none',            color: 'black'        }}    >        {children}    </NavLink> ) 
like image 553
Max Wolfen Avatar asked Mar 22 '18 10:03

Max Wolfen


People also ask

How are arrow functions () => {} different than traditional function expressions?

Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

What are the functions of arrows?

Arrow functions introduce concise body syntax, or implicit return. This allows the omission of the curly brackets and the return keyword. Implicit return is useful for creating succinct one-line operations in map , filter , and other common array methods.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

When an arrow function's body is left without curly braces What changes in its functionality?

Without curly braces {} . With this syntax, the arrow function has an implicit return. For example, the below arrow function returns 42, even though there's no return .


1 Answers

Using ({}) is to destructure the arguments and => () is an implicit return equivalent to => { return ()} and ( only serves to disambiguate between the start of an object and the opening braces of a function body and would generally be used when you have a multiline return value. You could simply avoid using ( and have the NavLink in the same line as the arrow =>

const FilterLink = ({ filter, children }) => ( // <-- implicit return    <NavLink     to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}     activeStyle={ {       textDecoration: 'none',       color: 'black'     }}   >     {children}   </NavLink> ) 

is equivalent to

const FilterLink = ({ filter, children }) => {    return (       <NavLink         to={filter === 'SHOW_ALL' ? '/' : `/${ filter }`}         activeStyle={ {           textDecoration: 'none',           color: 'black'         }}       >         {children}       </NavLink>     ) } 

Check this answer for more details on the usage of destructuring in ({ filter, children })

like image 54
Shubham Khatri Avatar answered Oct 14 '22 03:10

Shubham Khatri