I am passing a set of params into the following function.
postData(
param1,
param2,
param3,
param4,
param5,
param6
);
But I only want to pass all params if a certain condition is met. Else I only want to send the first 3 params.
I could do something like the following.
const condition = // true or false;
if (condition) {
postData(
param1,
param2,
param3,
param4,
param5,
param6
);
} else {
postData(
param1,
param2,
param3
);
}
But is there a more elegant way to do this instead of this in Javascript?
Update:
const postData = (item1, item2, item3, item4, item5, item6) => {
return `${item1} ${item2} ${item3} ${item4} ${item5} ${item6}`;
}
const check = true;
const appDiv = document.getElementById('app');
appDiv.innerHTML = `${postData('param1', 'param2', 'param3', ...check ? ['param4, param5, param6'] : [] )}`;
When condition is true, ends up printing the following:
param1 param2 param3 param4, param5, param6 undefined undefined
Here's an example of working DRY:
If the order of your parameters is as you described then:
const params = [param1, param2, param3, param4, param5, param6];
postData(...params.slice(0, condition ? 99 : 3)); // large-enough number
As you can see, this simply takes the array (of params) and using rest together will slice will only take those which you need and use them as a chain of parameters.
Alternatively, another DRY method would be:
console.log( ...[1,2,3].concat(true ? [4,5] : []) )
console.log( ...[1,2,3].concat(false ? [4,5] : []) )
// first method, where order of the array of params is fixed:
console.log( ...[1,2,3,4,5].slice(0, true ? 99 : 3) )
console.log( ...[1,2,3,4,5].slice(0, false ? 99 : 3) )
You can use the rest operator (...) and arrays to do it:
const params = [param1, param2, param3, param4, param5, param6];
if (condition) {
postData(...params);
} else {
postData(...params.slice(0, 3)); // slice out the first 3 parameters
}
Note that this method is not quite equivalent since all of the parameters will be immediately evaluated to form the initial array, so expensive/stateful calculations may behave differently. Something that would behave more similarly might look like this:
postData(param1, param2, param3, ...condition ? [param4, param5, param6] : []);
You can use conditional operators:
condition ? functionIfConditionIsTrue(params) : functionIfConditionIsFalse(params);
And another example are the 3-dots in function parameters:
let params = [param1, param2, param3, param4, param5, param6];
(condition ? postData(...params) : postData(...params.slice(0, 3));
More about conditional operators at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator