Tell us what’s happening:
Describe your issue in detail here.
Hello, i was wondering in line 6 of this code why is it repeated along with line 5?
Your code so far
// Only change code below this line
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
// Only change code above this line
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Use Recursion to Create a Countdown
hey bro thx for responding, no not that im talking about the line “arr.unshift(n)” . How is it that line will repeat, depending on the value n , even though there’s nothing to make it do so, atleast i dont see anything that would prompt it that line to repeat
So after the recursive call to countdown returns a value then arr.unshift(n) will be executed. What’s making it do that is the fact that you wrote arr.unshift(n) after the line that makes the recursive call. But perhaps I am not understanding your question correctly?
Hola, si no entiendo mal la pregunta querés saber cómo se obtienen valores de manera repetida? No llego a entender, pero suponiendo que sea eso, básicamente en la línea de la recursion se llama a la propia función desde dentro de si misma con un valor de n-1 y el resultado se guarda en arr, para luego insertarle n al inicio de arr ( que es un array). Por ejemplo, si llamas a la función con 2, salta el if, se mete en el else y en el else se llama a la función con un 1, en esa llamada el 2 va a saltarse el if, se mete en el else y en el else se llama a la función con un 0. Finalmente en esa llamada entra en el if y se retorna un array vacío, que se va a guardar en la variable arr de la llamada anterior, luego a esa variable arr se le insertará el 0 y se retornará arr que se guardará en la variable arr pero de la llamada anterior. A esa variable se le insertará el 1 con el que fue llamada la función en la primer recursion y se retornará ese array a la primer llamada recursiva y se guardará en arr de la primer llamada y luego se le insertará el 2 al principio del array para luego retornar el array a la llamada inicial.
yeah your getting the question right bro, i think im getting it, just to clearify though, in the else block despite the return statement being witin the same block, only every other line will recurse until the base case it met?