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

253
Vistas
How to return false with message in Javascript

It is possible to return false with some message?

function test(){
  if(5 > 6){
    return false;
    return 'message'
  }
  if()
  
  if()
}

I know - above example does not works. I will use this function in different part of code, and if test function return false I would like to throw an error with message

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

0

You can return an object:

function test(){
  if(5 > 6){
    return {
      result: false,
      message: 'message'
    }
  }
  ....
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You cannot use return twice, as the code will terminate after the first return statement and return the corresponding value, but what you can do is return an object like this with as many params as you want, and then use them as you like

function test() {
    if (5 < 6) {
        return { status: true, message: 'message' }
    }
}

const { status, message } = test();
console.log(status, message);

about 4 years ago · Juan Pablo Isaza Denunciar

0

function test() {
  if (5 > 6) {
    return false;
  }
  return true;
}

if (!test()) {
  throw new Error('FALSE returned');
}

How about that? Or better in the context of your example (since you plan to re-use that function):

function test() {
  if (5 > 6) {
    throw new Error('5 is not greater than 6.'); // error message is relevant to this function
  }
  // do something else
}

try {
  test();
} catch (e) {
  throw new Error('test() threw error.'); // error message is relevant to wherever it's called
}

You can still access the original error message in e.message.

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