Javascript basic codes

Tell us what’s happening:
Describe your issue in detail here.
my cade is doing what it is supposed to do then why is the compiler showing an error

  **Your code so far**

// Only change code below this line
var array = [];
function countdown(n){
if(n<1){
  return [];
} else {
  array.push(n)
  countdown(n-1);
  return array;
}

}
countdown(10);
console.log(array)
// Only change code above this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

You are using a global variable for your array - it is outside the scope of your function and is in the global scop. That means that it will “save” the value from the previous run. For example, if I put this at the bottom of your code:

console.log(countdown(3));
console.log(countdown(3));
console.log(countdown(3));

This is the output I get:

[ 3, 2, 1 ]
[ 3, 2, 1, 3, 2, 1 ]
[ 3, 2, 1, 3, 2, 1, 3, 2, 1 ]

This is one of the reasons why global variables are frowned upon.

2 Likes

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