I saw a JS syntax as following:
export const ChartComponent = props => {
const {
data,
colors: {
backgroundColor = 'white',
lineColor = '#2962FF',
textColor = 'black',
areaTopColor = '#2962FF',
areaBottomColor = 'rgba(41, 98, 255, 0.28)',
} = {}, // what is that curly brace?
} = props;
...
}
I’ve read the destructuring assignment, but I still don’t know what the curly braces do?
It seems a default value for colors
, but I don’t know why.
As far as I know:
- the syntax only assigns destructuring values to
data
/backgroundColor
/lineColor
/textColor
/areaTopColor
/areaBottomColor
, not includingcolors
. - The destructuring variables (
backgroundColor
/lineColor
/textColor
/areaTopColor
/areaBottomColor
) already have their own default values.
Is the curly braces for color
necessary? What does it do?
2
Answers
The
= {}
is there to cover for one edge case:If you DO have a
props
value that is an object, but it DOES NOT have a property namedcolors
or the property is there but IS NOT a destructurable object.For example:
You would have:
In this context,
{}
is just an empty object, used as a default value (you could have used any other object value). It will be used in case no destructurable object can match a property with namecolors
.the answer given by @Rodrigo Rodrigues explains the reason. I will give an example
Lets say the
props
doesn’t havecolors
. Then in the destructuringcolors
will beundefined
and it looks like trying to destructure the propertiesbackgroundColor
etc. from an undefined. Even though you have the default values forbackgroundColor
it can’t destructure the undefined.Now with the
{}
it handles this case and assigns a default{}
whencolors
in not found in props. After that it tries to destructure that empty object which is possible. Since thenbackgroundColor
is not present in the{}
it will be assigned with the default value forbackgroundColor
which is white