This syntax is related to object dectructuring (see examples) and is common in React as a component can be declared as a function of a single object called props.
Instead of writing:
var Hello = (props) => {
return <div>Hello {props.name} from {props.city} with {props.item}</div>;
}
You can reduce it to this form:
var Hello = ({name, city, item}) => <div>Hello {name} from {city} with {item}</div>
In your example it destructures the props
to properties para1
and para2
.
var works = ({para1, para2}) => console.log(para1, para2)
works({para1: 'test', para2: 'another one'})
works({para2: 'another one', para1: 'test', anotherProp: 'does not matter'})
As you can see order of passed properties doesn't matter. Contrary to default argument list syntax. This behavior may be favorable in React apps as components tend to accept multiple named properties.
Syntax issues
Without braces around object destructuring in function arguments you would get a syntax error because it is being parsed as an object literal.
var doesntWork = {para1, para2} => console.log(para1, para2)
Same issues occur when you want to return an object within an arrow function, which can lead to undesired behaviour. For example, this code will return and print undefined
.
var add = ({a, b}) => {sum: a + b}
var result = add({b: 3, a: 5})
console.log(result)
The brackets are parsed as a code block, not an expression. To fix the code it should be wrapped with braces: var add = ({a, b}) => ({sum: a + b})
Object and array destructuring is a powerful tool which make stateless functional components in React possible and viable. Code becomes simpler and more readable.