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){
sad.push(n)
return (n==1)?sad:(n<1)?[]:countdown(n-1);
}
console.log(countdown(5))
// 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.
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.
Example:
var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run
function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2
No reason to “my bad” you’ve not offended anyone
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