Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
Send some or all params into a function based on a condtion

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
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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) )

about 4 years ago · Juan Pablo Isaza Relatório

0

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] : []);
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda