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

277
Vistas
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 Respuestas
Responde la pregunta

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