How do you give a prop a default value in a modern function component?
Use default values in the destructured parameters, such as function Badge({ color = 'blue' }). The default applies only when the prop is undefined, not when it is null or an empty string.
Explain it simply
A default prop is like the sugar a chaiwala adds when you do not say anything. If you ask for no sugar, he respects that. In code, the default only fills in when the value is truly missing, meaning undefined.
defaultProps on function components is deprecated in recent React versions, so default values in the parameter list are the standard approach.
A quick way to remember it: the default is a fallback for a missing answer, not for a wrong one. If a parent passes 0, false or an empty string on purpose, those are real values and they win over the default. When the parent computes a value that may be missing, convert it to undefined yourself if you want the default to apply.
Example
function Badge({ label, color = "blue", size = 14 }) {
return <span style={{ color, fontSize: size }}>{label}</span>;
}
<Badge label="New" /> // blue, 14
<Badge label="Hot" color={undefined} /> // blue, undefined triggers default
<Badge label="Off" color={null} /> // null stays null, no defaultWhat to say in the interview
"I use JavaScript default parameter values in the destructuring. They apply only for undefined, so null or empty string will not trigger them. Function component defaultProps is deprecated, so I avoid it in new code."
Common mistakes
- Expecting null to trigger the default.
- Using an object default like style = {} inline and expecting a stable reference across renders.