Kirk Strobeck Kirk Strobeck - 1 month ago 6
Javascript Question

Is it possible to destructure function arguments with ternary assignment?

I would like to be able to destructure function arguments with ternary assignment.

Is there any variation of this that’s possible?

const fn = (size ? 'large' : 'small') => `image${size}`;

fn(true); // imageLarge
fn(); // imageSmall





Edit, better explanation of the use-case




const fn = (size ? 'large' : 'small') => [
`lots${size}`,
`of${size}`,
`values${size}`,
];

fn(true); // imageLarge
fn(); // imageSmall

Answer

You can do that using default parameters:

const fn = (isLarge, size = isLarge ? 'large' : 'small') => [
  `lots${size}`,
  `of${size}`,
  `values${size}`,
];

console.log(fn(true));

console.log(fn(false));