Should I work harder on shorter code?

Tell us what’s happening:
I’m still a beginner in programming and I’m having rather a hard time getting the hang of algorithms; and I’ve got two questions which answers will be most appreciated.

First: I’ve compared my answer to the solutions shown in the “Get Help” tab and noticed that, always, my answers are SOo much longer than the latter. Should I be spending time trying to optimize my code, or should I just keep on moving on as long as I get the problems correct?

and Second: I don’t understand why the ‘Return’ in line 25 is necessary. I tried Ctrl+Enter-ing without that return, but it wouldn’t lead me to the correct answer. My thought process on that is that there are already two ‘Returns’ in line 13 and 22 which makes recalling on the output unnecessary.

  **Your code so far**

function factorialize(num) {
if (num == 0) {
  console.log('1');
  return 1;
} else {
 
    function arrayOfNum(num) {
      let arrayNum = [];
      for (let i = 1; i <= num; i++){
        arrayNum.push(i);
      }

      return arrayNum;
    }

    function arrayToMultiple(x) {
      let multipleNum = 1;
      for (var j = 0; j <= x.length-1; j++){
        multipleNum = multipleNum * x[j];
      }

      return multipleNum;
    }

  return arrayToMultiple(arrayOfNum(num));
    }

  
}


factorialize(5);
  **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.131 Safari/537.36

Challenge: Factorialize a Number

Link to the challenge:

I generally would not worry about ‘short’ code. That will come with practice and time.

That said…

this is not a good solution.

You set the function up to be recursive, but this is not at all recursive. This is a bunch of extra complexity that you do not need.

There are two approaches to this problem

  1. Use a simple loop (this is the best approach)

  2. Use recursion (this is worth practicing)

1 Like

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