Return command in recursion

why does ‘return 1’ do this? i thought that would literally return 1 as a result, rather than the multiplication result.
(i also wrote a summing function which only works with return 0.
not understanding the return command here)

  function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

Challenge: Replace Loops using Recursion

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

It does literally return 1.

if (n <= 0) {
  return 1;
}

This causes the function to return 1 when n <= 0. So if you called the function as:

multiply([5,6,7], 0)

Then the function would return 1;

So why would you ever call this function with 0 passed in as the second argument? Well, look at what the else block is doing each time it returns.

2 Likes

It does return 1. Look:

multiply([1,2,3], 0)

That returns 1, n <= 0, so it’s 1.

So 1.

multiply([1,2,3], 1)

n <= 0 is false, so

return multiply([1,2,3], 0) * 1

You know multiply([1,2,3], 0) is 1, so 1 × 1 is 1.

So 2.

multiply([1,2,3], 2)

n <= 0 is false, so

return multiply([1,2,3], 1) * 2

You know multiply([1,2,3], 1) is 1, so 1 × 2 is 2.

So 3.

multiply([1,2,3], 3)

n <= 0 is false, so

return multiply([1,2,3], 2) * 3

You know multiply([1,2,3], 2) is 2, so 2 × 3 is 6.

2 Likes

wat about

multiply( [2,3,4] , 0)

it returns 1?

Well, what is n in that case?

1 Like

zero. nada. nowt. zilch.
0

Right, so what happens when n <= 0?

1 Like

it returns 1 so it does

2 Likes

which is wrong, no?
or whata bout my sum code (which is logged as ‘pass’)

function sum(arr, n) {
  if(n<=0){
    return 0
  }else{
    return sum(arr,n-1)+arr[n-1];
  }
  }
console.log(sum([2,3,4,5],3))

this returns the func value + whatever the IF statement is told to return (0 therefore works, but why would it return [ELSE func + return ‘x’ of IF] statement?)

Why would it be wrong? I don’t see a reason for it to be wrong. The product of n = 0 elements should be equal to 1.


Not quite. The return statement

    return sum(arr, n-1) + arr[n-1];

adds together the result of calling the function with the argument n - 1 (which represents taking the sum of the first n - 1 elements in the array) and the nth element of the array (at index n - 1).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.