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);
}
printthat results in the error you describe?