-5

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

ProteinDev
  • 79
  • 5
  • 4
    You can only return once. But if you want to send multiple values you could use an object like `{status: false, message: 'some message'}` – Reyno Oct 19 '21 at 10:21
  • You want to throw an error or do you want to return two thinhs - which is it? – VLAZ Oct 19 '21 at 10:21
  • You can only return _one_ thing at a time - but that one thing could be a more complex object. But whether using something like `return [false, 'message'];` would serve any _purpose_ returning false might originally have had, might be doubtful. – CBroe Oct 19 '21 at 10:22

5 Answers5

0

You can return an object:

function test(){
  if(5 > 6){
    return {
      result: false,
      message: 'message'
    }
  }
  ....
}
Joao Leal
  • 5,533
  • 1
  • 13
  • 23
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);
AnanthDev
  • 1,605
  • 1
  • 4
  • 14
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.

msrumon
  • 1,250
  • 1
  • 10
  • 27
0

You can return object inserted of single variable

function test() {
  if (5 > 6) {
    return {status: false, message: 'My custom message'};
  }
  if (5 < 6) {
    return {status: false, message: 'My custom message'};
  }
}
var response = test();
response.status; // true/false
response.message; // My custom message
Shubham Sharma
  • 479
  • 4
  • 8
0

No, you can't do that since return stops the execution of the function, so any code below it won't be executed. As a workaround, you could just return an array of false and the message.

function test(){
  if(!(5 > 6)){
    return [false, 'message'];
  }
}

let res = test();

console.log(res);
console.log(res[0]);  //to access false
console.log(res[1]);  //to access the message
TechySharnav
  • 4,869
  • 2
  • 11
  • 29