Help explain why the result is 2.

function fun(n) {
  if (n < 0){
    return 0
  }
  if (n === 1){
    return 1
  }
  if (n === 2){
    return 2
  }
  return fun(n-1)
}
console.log(fun(4))  //2
Jun.16,2022

Dear, this is a recursion. When executing fun (4), no matching result will be return fun (3), and there will be no matching result when executing fun (3). It will continue to execute fun (2). When fun 2 matches, it returns 2. The result is recursive


from top to bottom trying to understand what is going on at each step. You will not ask this question


recursive operation. Every time the execution does not meet the above conditions, the parameters are put in and executed again. Know that the result returned by meeting the if condition


recursively has no matching result until nasty 2 returns 2.

Menu