JavaScript: Using recursion to create countup | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript: Using recursion to create countup

https://code.sololearn.com/WnLSAX5PKls7/?ref=app How this code returns [1,2,3,4,5] as output? I analyzed this function as follows, Since n=5; const countArray=countup(5-1); countArray.push(5) return countArray; // [5] n=4, const countArray=countup(4-1); countArray.push(4) return countArray; // [5,4,] n=3, const countArray=countup(3-1); countArray.push(3) return countArray; // [5,4,3] n=2, const countArray=countup(2-1); countArray.push(2) return countArray; // [5,4,3,2] n=1, const countArray=countup(1-1); countArray.push(1) return countArray; // [5,4,3,2,1] Where I went wrong here, How to analyze this code correctly ?

14th Jul 2020, 6:04 AM
Ajitha G R
Ajitha G R - avatar
3 Answers
+ 1
when constArray=countup(5-1) it doesnt continue to countArray.push immediately instead it goes into the countup function, so countup(4-1) will run. here is the process n=5 constArray=countup(5-1) n=4 constArray=countup(4-1) n=3 constArray=countup(3-1) n=2 constArray=countup(2-1) n=1 return [] countArray.push(1) return countArray countArray.push(2) return countArray countArray.push(3) return countArray countArray.push(4) return countArray countArray.push(5) return countArray
14th Jul 2020, 6:29 AM
Taste
Taste - avatar
0
Taste Thanks a lot .Clear answer
14th Jul 2020, 6:43 AM
Ajitha G R
Ajitha G R - avatar
- 1
I hate JavaScript
14th Jul 2020, 6:40 AM
Misa