Search code examples
javascriptjavascriptcoredefault-parametersdestructuring

JavaScript nasted default parameters


Lets say I want to process some property x of objects in collection array. But collection may contain objects without such property or even undefineds. For example

let array = [
  {x: 1},
  {x: 2},
  {},
  {x: 4},
  undefined
]

The idea is protect my self from such edge cases with default parameter. Let it be 0. I was trying to solve this as

array.map(({x: x = 0}) => process(x))

But it fails on undefined. Is there any way to solve this issue with default parameters and destructuring without writing check/set code inside of map function?


Solution

  • You can give the default object a default value

    array.map(({x : x = 0} = 0) => process(x));