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

254
Visualizações
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 Respostas
Responde à pergunta

0

You can return an object:

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

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 Relatório

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