Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!