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

289
Visualizações
In JavaScript Is it better to throw an exception first then return the value or vice versa?

Let's say value argument may be string or null

function doSomething1(value) {
  if (value) {
    // do something
  }

  throw new Error("No value provided");
}

function doSomething2(value) {
  if (!value) {
    throw new Error("No value provided");
  }

  // do something
}

In that case, I want to check the value and throw an error if it's null.

Question: Is there any technical difference in terms of performance or memory usage between the functions doSomething1 and doSomething2 considering that // do something part may be small or huge? Will the order of exception throwing influence the performance at any level at all or is it 100% identical use cases?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There's absolutely no difference in terms of runtime:

In both cases, if value is null, you have one boolean check and an error throw, otherwise you have one check and the execution of the // do something block.

The difference is purely code style. I personally prefer the second one as it reduces the indent level by one on // do something, and puts error handling all in one place (whereas in the first one, you have the check at the beginning of the method and the throw at the end).

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