Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
How to remove multiple if statements in javascripts

I have following piece of code.

  a = []
   b = []
   c = []
useEffect(() => {

if(isEmpty(a) && isEmpty(b) && isEmpty(c)) {
   data.refetch()
}
if(data.isFetching){
  //do something
}

if(response.isFetching){
  //do something
}

}, [ //Some depedencies ])

SO, is there any way through which I can modify this if statements. As I tried with the switch statements but it is not helping over here. So, Any suggestion would e great. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can remove every if of the code in the following way:

a = [];
b = [];
c = [];
conditions = [
[[a,b,c].every((x) => isEmpty(x)), () => data.refetch()],
[data.isFetching, someOtherFunction],
[response.isFetching, anotherFunction]
];
conditions.forEach(cond => cond[0] && cond[1]());

I would not recommend this as it makes your code less readable and confusing.

Explanation:

The function every will test condition for every element of an array and joining with an and:

...
 [a,b,c].every((x) => isEmpty(x)) 
...

Then to test every condition you can add them to an array and iterate through them, with a callback for every if you want to create:

conditions = [
[[a,b,c].every((x) => isEmpty(x)), () => data.refetch()],
[data.isFetching, someOtherFunction],
[response.isFetching, anotherFunction]
]
condtions.forEach((cond) => { if(cond[0]) cond[1]() } )

Then As suggested by derpirscher you could remove the last if with

conditions.forEach(cond => cond[0] && cond[1]());

But again, this makes your code more confusing, I would suggest keeping the ifs to make it more clear.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda