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

136
Vistas
What is the best practice when return different types(object) by condition in javascript?

I'm writing a function to validate for input arguments. But I'm not sure it's the best practice to use.

I have a function that validates like this,

const isValidStudyId = (id) => {
  if (validator.isUUID(id) === false || isValidArguments([id]) !== true) {
    console.log(`${id} is invalid Study Id`);
    return { valid: false, message: `${id} is invalid id!` };
  }
  return true;
}

And use this like this,

  const isValidId = utils.isValidStudyId(studyId)
  if (isValidId !== true) {
    res.status(400).send({
      message: isValidId.message
    });
    return;
  }

And I don't like the way it check validity like

if (isValidId !== true)

this way. Because it's returning sometimes boolean, sometimes an object. Could you suggest other ways to do? I'm not very familiar with the javascript, and I wanna learn more about what is the best practice in this sort of situation.

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

0

Change it to validateStudyId instead that returns a message why it's invalid if it's invalid, otherwise returns a falsy value.

const validateStudyId = (id) => {
  if (validator.isUUID(id) === false || isValidArguments([id]) !== true) {
    const message = `${id} is invalid Study Id`;
    console.log(message);
    return {
      valid: false,
      message
    };
  } // else undefined
}

and then you can just test it like it's boolean and even chain several such checks together in a way that stops at the first truthy response, like this:

const o = validateStudyId(id) || validateOtherThing() || validateThirdThing();
if (o) {
  res.status(400).send(o); // no need to create a new object
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

The Normal Way

If you're referring solely to what structure you should use, perhaps returning something like {valid: true} and check the valid property, as the message property is only checked when valid is false, it's not necessary to set one when valid is true, unless you want to.


The Weird (and maybe ever so slightly nonstandard) Way

Another option would be to use something like callback functions to structure your flow differently.

// 'next' is a function that takes two arguments (error, message)
const checkStudyID = (id, next) => {
    // '=== false' is somewhat redundant if these checks always return booleans
    if(!validator.isUUID(id) || !isValidArguments([id])) {
        console.log(`${id} is an invalid Study ID`);
        return next(true, `${id} is invalid id!`);
    }
    next(false);
}

// --- USAGE ---
utils.checkStudyId(studyId, (err, msg) => {
    if (err) return res.status(400).send({message: msg});
});
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