Javascript lesson 110 basics undefined

Tell us what’s happening:
hi i dont know why there say undefined if i put console.log(), how can i prove watching what contain myArray afther the function. i guest is wrong. to count down doesnt it use unshilft()?

Your code so far


//Only change code below this line
var myArray = new Array();


function countdown(myArray, n){
if(n <= 0){
  return myArray;
}
else{
  myArray.push(n);
  countdown(myArray, n - 1);
}
}

console.log(countdown(myArray,5));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

The reason why you’re returning undefined is because you don’t have a return called when you enter recursion. The simple fix for this is to add a return statement in front of your countdown so your code would look like this:

var myArray = new Array();


function countdown(myArray, n) {
    if (n <= 0) {
        return myArray;
    } else {
        myArray.push(n);
        return countdown(myArray, n - 1);
    }
}

console.log(countdown(myArray,5));

The alternative is you can add a console.log(myArray) inside your base case which would output the array. However, you would still return an undefined value.

3 Likes