I have a function that performs an AJAX call, as such:
let retrieveData = (section, sectionItem, callback) => {
...
}
Where the second parameter is optional, i.e. in some cases that parameter is required, in others it isn't:
let data = retrieveData(aSection, aSectionItem, function(json)) {
...
});
and:
let data = retrieveData(aSection, undefined, function(json)) {
...
});
In the second instance I'd like to be able to omit the undefined
parameter and I believe assigning options/defaults by way of destructuring is the answer (as per this example: https://javascript.info/destructuring-assignment#smart-function-parameters), but I'm coming up short on how to structure the code.
You current way :
let retrieveData = (section, sectionItem, callback) => {
console.log('Section :', section);
console.log('Section item :', sectionItem);
console.log('Callback :', callback);
}
retrieveData('a', 'b', () => {});
retrieveData('a', undefined, () => {});
sectionItem
is omitted, it'll be undefined
.let retrieveData = ({ section, sectionItem, callback }) => {
console.log('Section :', section);
console.log('Section item :', sectionItem);
console.log('Callback :', callback);
}
retrieveData({
section: 'a',
sectionItem: 'b',
callback: () => {}
});
retrieveData({
section: 'a',
callback: () => {}
});
sectionItem
:let retrieveData = ({ section, sectionItem = 'defaultValue', callback }) => {
console.log('Section :', section);
console.log('Section item :', sectionItem);
console.log('Callback :', callback);
}
retrieveData({
section: 'a',
sectionItem: 'b',
callback: () => {}
});
retrieveData({
section: 'a',
callback: () => {}
});
sectionItem
to the end of the function, making it easier to omit.let retrieveData = (section, callback, sectionItem) => {
console.log('Section :', section);
console.log('Section item :', sectionItem);
console.log('Callback :', callback);
}
retrieveData('a', () => {}, 'b');
retrieveData('a', () => {}); // Here you omit the parameter
let retrieveData = (options) => {
console.log('Section :', options.section);
console.log('Section item :', options.sectionItem);
console.log('Callback :', options.callback);
}
retrieveData({
section: 'a',
sectionItem: 'b',
callback: () => {}
});
retrieveData({
section: 'a',
callback: () => {}
});
Please use optional arguments and deconstruct your parameters.
const foo = (section, {sectionItem, callback} = {}) => {
console.log(section, sectionItem, callback);
}
So both sectionItem
and callback
are optional:
let data = retrieveData(aSection, {
sectionItem: 'some',
callback: json => {
...
},
});
This way you can call either of:
retrieveData(aSection)
retrieveData(aSection, {sectionItem: 'some'})
retrieveData(aSection, {callback: json => { ... }})
Another important aspect is you keep optional arguments verbose right from the caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With