Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructing an object being function's argument with default property

I want to pass an object as an argument to the function. If property 'prop' of this object is undefined, it should be initialized by default value.

How to do it using modern JS?

I expect something like this:

const fun = function(options = { prop: 'default'}) { console.log(options.prop)}


fun({a: 'x', prop: 'hello'}) ... // log: 'hello'

fun({a: 'x'}) ... // log: 'default'
like image 463
Asker Avatar asked Jan 27 '23 10:01

Asker


1 Answers

If you want to destructure in the parameter list, you won't have access to the entire original object (the options, here) anymore - you'll only have the destructured variables. So, leave out the options = part, and put the = after the prop, instead of :. For example:

const fun = function({ prop = 'default', a }) {
  console.log('prop:', prop, 'a:', a);
};

fun({
  a: 'x',
  prop: 'hello'
}) // log: 'hello'

fun({
  a: 'x'
}) // log: 'default'

If the function also may not be called with any parameters, you may default-assign an empty object:

const fun = function({ prop = 'default', a } = {}) {
  console.log('prop:', prop, 'a:', a);
};

fun({
  a: 'x',
  prop: 'hello'
}) // log: 'hello'

fun({
  a: 'x'
}) // log: 'default'

fun(); // log: 'default'
like image 82
CertainPerformance Avatar answered Jan 29 '23 14:01

CertainPerformance