Freecodecamp: Code gives good results but cant pass

Created on 20 Sep 2016  路  2Comments  路  Source: freeCodeCamp/freeCodeCamp

Challenge Name

Factorialize a Number

Issue Description

The problem is that my code gives good answers, at least when I'm checking different possibilities, but I'm not able to get green mark.

Browser Information

  • Browser Name, Version: Chrome 54.0.2840.27 beta-m (64-bit)
  • Operating System: Windows 10
  • Mobile, Desktop, or Tablet: Desktop

Your Code

var sum=[];
var kupa=1;
function factorialize(num) {
  for(var i=1; i<=num; i++){
    sum[i-1]=i;
  }
  for(var u=0; u<sum.length; u++){
    kupa*=sum[u];
  }
  return kupa;
}

factorialize(5);


Screenshot

untitled

Most helpful comment

@Struziu

The way we test the code does not play well with global variables.

In this case sum and kupa do not get initialised between tests and so retain the value assigned to them from the previous test.

Try moving sum and kupa inside the scope of factorialize(), this way, they will be initialised for each test.

If you would like to learn more about scope and why global variables are not the best thing to be coding with, have a read of the You don't know JS series. You can read it for free here. The book titled Scope & Closures will give you an insight into why your solution for this challenge didn't quite work.

Happy coding :+1:

All 2 comments

@Struziu you have global variables in your code. Your code is run consecutively after each test so those variables are modified. Your code will work if you put those variables within your function. If you get stuck or have questions with a challenge in the future, please first ask questions to the Help Room. Happy coding!

@Struziu

The way we test the code does not play well with global variables.

In this case sum and kupa do not get initialised between tests and so retain the value assigned to them from the previous test.

Try moving sum and kupa inside the scope of factorialize(), this way, they will be initialised for each test.

If you would like to learn more about scope and why global variables are not the best thing to be coding with, have a read of the You don't know JS series. You can read it for free here. The book titled Scope & Closures will give you an insight into why your solution for this challenge didn't quite work.

Happy coding :+1:

Was this page helpful?
0 / 5 - 0 ratings