Basic JavaScript: Recursive Function

Hi, guys!
It is my second week after 1 year of break in learning Java Script.
I’ve found this concept a bit difficult for me (I’ve spent whole day) to find a solution and I’d like to read your feedback about my version of this solution.

Thanks, a lot. :slight_smile: )



function sum(arr, n) {
/********* FINAL SOLUTION  RESULT: 0,2,9*********/

var numb = arr.length  -1;

 //base case
  if( arr.length <= 0){
      return 1;
  //recursive function
  }else if( arr.length >=  0 ){ 
      return sum(arr.length - 1, n), numb * n;    
  }
}

console.log(sum([1],0));
console.log(sum([2, 3, 4], 1));
console.log(sum([2, 3, 4, 5], 3));
/********** FINAL SOLUTION **********/

//**********************************************
/* TRY WITHOUTH EXTERNAL VARIABLE. RESULT IS 0,3,12 */

   /* if(arr.length <= 0){
        return 0;
      }else if(arr.length >= 0){
        return sum(arr.length - 1, n), arr.length * n;       
    } */

//**********************************************

/* TRY USING FOR LOOP */
//I've tried a for loop to find a solution before a recursive approach

      /*for(i = 0; i < arr.length; i++){
        var sum = arr.length - 1;
        return sum * n;
      }*/


Do you have a working solution or do you need help with one? In either case, we would need to see your code in order to comment.

1 Like

Yes, it works. I just want someone to tell me if it is a good solution and maybe some suggestion for my code and this topic.

Should I send my Codepen link?

You can share your code here.

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.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like