How to set default value in JavaScript’s Destructuring
Did you know that it's possible to set default value in Javascript object destructuring?
Let see how it works in action:
> { firstName = "John" } = {}
{}
> firstName
'John'
One thing to keep in mind is that it only works with undefined
values. It won't work with null
, false
and 0
as these are normal values.
> { firstName = "John" } = { firstName: null }
{ firstName: null }
> { firstName = "John" } = { firstName: 0 }
{ firstName: 0 }
> {firstName = "John"} = { firstName: false }
{ firstName: false }