Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter object with deconstruction

How do I make the second parameter optional and use deconstruction?

So far this works, but it's a bit ugly. Anything better?

const fn = (required, optional = {id: undefined, name: undefined}) => {
  const {id, name} = optional
  console.log(required, id, name)
}

fn('hello') // hello undefined undefined
fn('hello', {id: 'world'}) // hello world undefined
fn('hello', {name: 'world'}) // hello undefined world

I found this for typescript, Optional deconstruction function parameter , but I don't think I can apply the solution without TS.

like image 417
garajo Avatar asked Dec 17 '25 17:12

garajo


1 Answers

The same approach as the typescript solution you found works in ES6 as well:

function fn(required, {id, name} = {}) {
  console.log(required, id, name)
}

Use the destructuring expression as the target for the defaulted parameter, not optional. Also I've dropped the explicit property initialisation with undefined, just using an empty object as the default value works fine.

like image 155
Bergi Avatar answered Dec 19 '25 21:12

Bergi