How does it shows incorrect on output

Tell us what’s happening:
Describe your issue in detail here.

   **Your code so far**

// Only change code below this line
var sad=[];
function countdown(n){
 return (n==1)?sad:(n<1)?[]:countdown(n-1);
// Only change code above this line
   **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

EDIT: My bad the “sad” array declaration is global . So using console.log() jams it in the memory.

Remove your console.log() statement, it is jamming up the test conditions. It works fine without it.

1 Like

Yeah, if you try:


the output is:

[ 1 ]
[ 1, 5, 4, 3, 2, 1 ]
[ 1, 5, 4, 3, 2, 1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]

…it fails

but individually (one console.log() at a time):


output is:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
1 Like

If, in the challenge, you click “Get Help” > “Get a Hint”, and then look at Solution 4…

it is very similar to yours, but doesn’t have that issue.

Because it uses no destructive global variable which I did, it’s a bad practice anyway but works to complete short challenges.

1 Like

The console.log has nothing to do with the issue with this code.

You shouldn’t use any global variable. Your function should always return an array and you should use that return value in your recursive call.

Global variables are never needed for recursion to work. ‘Destructive’ global variables wouldn’t help, whatever those may be.

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.


var myGlobal = [1];
function returnGlobal(arg) {
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  return myLocal;
} // reliable - always returns an array of length 2

I didn’t really understand why theirs wasn’t working, my thinking was that it was appending each time, but I didn’t understand how or why.

Initially thought it had something to do with that global variable.

I just put the console.log() output example to show that the output is not what was expected, therefore test fail.

Thanks for making that clear! Your explanation make sense and now I have learned something new! :smiley:


No reason to “my bad” you’ve not offended anyone :smiley:
rather the forums have worked as intended…

one person makes a coding error… realizes mistake… another student learns something about the effect of using globals to store recursion values… win-win


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