---
title: "Discussion on \"I still dont get this recursion example...\" | Hashnode"
description: "Discussion on \"I still dont get this recursion example...\". https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion\nI don't understand why we get 9 and not zero when n is 0.\nfunction sum(arr, n) {\n  // Only change code below this line\n  if(n ..."
url: "https://hashnode.com/posts/i-still-dont-get-this-recursion-example/5ebdd181d48ffc3e79694aec"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [I still dont get this recursion example...](https://hashnode.com/post/i-still-dont-get-this-recursion-example?utm_source=hashnode&utm_medium=feed)

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion I don't understand why we get 9 and not zero when n is 0. function sum(arr, n) { // Only change code below this line if(n ...

May 14, 2020 · hashnode.com  
Read the article

-   [#javascript](https://hashnode.com/tag/javascript)

## Written by

[miguelmanalo](https://hashnode.com/@miguelmanalo)

@miguelmanalo

  
[View profile](https://hashnode.com/@miguelmanalo)

## Responses 1

Markdown supported · ⌘↵ to post

[j](https://hashnode.com/@chilimatic)

[May 15, 2020](https://hashnode.com/posts/i-still-dont-get-this-recursion-example/5ebdd181d48ffc3e79694aec/comment/5ebece5e5b588e782c1916ea)

because it's and addition in the end.

although I would use

```
const arr = [2,3,4,5];

console.log(sum(arr, arr.length));
```

```
 -> sum: [2,3,4,5], 3
  - 3 > 0 
  - return sum([2,3,4,5], 2) + 4
 -> sum: ...., 2
  - 2 > 0 
  - return sum(....., 1) + 3;
 -> sum: ....., 1
  - 1 > 0
  - return sum(...., 0) + 2
 -> sum: ....., 0
  - 0 == 0
  - return 0
```

which means:

```
first call (4) + second call (3) + third call (2) + forth call(0)
4+3+2+0 -> 9;
```

does this make sense?

a more visual approach would be if you just pop the value before passing

```
const val = arr.pop();
return sum(arr, arr.length) + val;
```

but since JS an array is just a specialized form of an object you actually would need to

```
const newArr = [...arr];
const val = newArr.pop();
return sum(newArr, newArr.length) + val;
```

to have no sideeffects. But this maybe is more confusing. it's just so the array you pass in as a reference does not get changed but you still see that the recursion your wrote basically is a stack call that removes one element after another and passes it to the previous call.

a question of taste so to say.

[miguelmanalo](https://hashnode.com/@miguelmanalo)

[May 16, 2020](https://hashnode.com/posts/i-still-dont-get-this-recursion-example/5ebdd181d48ffc3e79694aec/comment/5ebece5e5b588e782c1916ea#reply-5ebfff3ba4db0c222f2222f8)

oh having it step by step is very very helpful, thank you!
