Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: correct way to set object parameters with name and default value

What I'm trying to do is to pass an object to a function, where certain default values may be set, and the whole object shall have a name to pass it to another function.

The following code, without naming the parameter, works just fine.

function test({
  item1,
  item2 = 0
}) {
  console.log(item1 + " " + item2);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}

But if I now start setting obj = {...} to pass to print() I get a syntax error:

function test(obj = {
  item1,
  item2 = 0
}) {
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}

If I write item2: 0, there will be no error, but then in print item2 is undefinded.


From the answers below, this seems to be the way that works best for me so far:

function test(obj) {
  obj = Object.assign({
    item1: undefined,
    item2: 0
  }, obj);
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}
like image 991
Don Fuchs Avatar asked Aug 02 '26 08:08

Don Fuchs


1 Answers

Destructuring extracts properties from an object passed to the function and puts those properties into standalone variables - that's all. What you're trying to do is mutate one of the parameters, not extract properties from the parameter into standalone variables.

You can't mutate parameters inside a parameter list - for the sort of logic you're looking for, you'll have to do it inside the function body of test:

function test(obj) {
  if (!obj.hasOwnProperty('item2')) {
    obj.item2 = 0;
  }
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}

If you have lots of properties you want to assign default values to, you can use Object.assign:

function test(obj) {
  const filledObj = Object.assign({
    item2: 0,
    item3: 'item3'
  }, obj);
  print(filledObj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj);
}

If you only want an object with certain properties to pass to print, then extract those properties in the parameter list like you're doing originally, then pass a reconstructed object of only those properties to print:

function test({
  item1,
  item2 = 0
}) {
  const obj = { item1, item2 };
  print(obj);
}

test({
  item1: "foo"
});

function print(obj) {
  console.log(obj.item1 + " " + obj.item2);
}
like image 50
CertainPerformance Avatar answered Aug 03 '26 22:08

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!