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

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

0

You can return an object:

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

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 Report

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