Search code examples
javascriptrecursionreturn

how return one of the function between OR operator?


I can not understand when the 'find' function will true or false in the else block. Here is the code:

function findSolution(target) {
  function find(current, history) {
    if(current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5 )`) || find(current * 3, `(${history} * 3)`);
    }
  }

  return find(1, "1");
}

console.log(findSolution(24));

Solution

  • || works by first evaluating find(current + 5, `(${history} + 5 )`) and if it is truthy that is the final result. If it is falsy it will evaluate find(current * 3, `(${history} * 3)`) and whatever is the result will be the end result which is then returned.

    You can replace return expra || exprb with code without || using if and bindings:

    // expra and exprb can be any valid expression
    // same as return expra || exprb;
    const tmp = expra;  
    if (tmp) {
        return tmp;
    }
    return exprb;