Home > OS >  Continue function if returned function is not returning
Continue function if returned function is not returning

Time:03-23

I am trying to reduce cyclomatic complexity but this is a general query. if function b is not returning anything function a should continue to return 3

function a() {
  return b();
  return 3
}

function b() {
  if (false)
    return 2
}
alert(a())

CodePudding user response:

More manually you could store the result of b() in a variable, check the variable, and conditionally return or continue. Though in this simplified version you could also just rely on the Nullish coalescing operator when returning.

For example:

function a() {
  return b() ?? 3;
}

function b() {
  if (false)
    return 2
}
alert(a())

Essentially the expression resolves to either the result of b() or, if that result is null or undefined, resolves to 3. Then the result of that overall expression is returned.

CodePudding user response:

That works with my test, "I used console.log not alert"

function a() {
  let val = b()
  return val == null ? 3 : val;
}

function b() {
  if (false) return 2;
  return null; // If anytings doesnt return that function we returns null 
}
alert(a());

Performance test for nullish operator or standart one line if https://jsbench.me/ool12lcckh

CodePudding user response:

Instead of directy returing b() inside a() you can set an if condition. So when b() returns a valid response then it returns b() if it returns false then a() returns 3. You can try this code below.

function a() {
  if(b()){
    return b()
  }
  else{
    return 3
  }
}

function b() {
  if (false){
    return 2
  }
  else{
    return false
  }
}
alert(a())

  • Related