Recursion: this code work very weird, better is use for loop,

Cuéntanos qué está pasando:
Describe tu problema en detalle aquí.
Hello Everybody, can somebody explain that behaibour

  **Tu código hasta el momento**
function countup(n) {

  if (n < 1) {
    return [];
  } else {
        console.log(n, " times ");  
    const countArray = countup(n - 1);
    
    console.log(countArray, n , " ??? ");
    
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5), "final");

This is the output

5  times 
4  times 
3  times 
2  times 
1  times 
[] 1  ??? 
[ 1 ] 2  ??? 
[ 1, 2 ] 3  ??? 
[ 1, 2, 3 ] 4  ??? 
[ 1, 2, 3, 4 ] 5  ??? 
[ 1, 2, 3, 4, 5 ] final


function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {
  return [];
} else if (startNum < endNum) {
  const countArray = rangeOfNumbers(endNum - 1);
  //countArray.push(n);

  
  console.log(startNum);
  var inic = startNum;

  //if (typeof countArray === 'undefined') { 
  //    const countArray = (endNum-1); 
  //} 
  
  

  countArray.push("inic");
  
  startNum += 1;
  countArray = rangeOfNumbers(inic, endNum);
      
  //console.log(countArray);
  
  return countArray;
} else {
  console.log(" termino ");
  return [];
}
}
console.log(rangeOfNumbers(1 , 5));
  **Información de tu navegador:**

El agente de usuario es: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59

Desafío: Usa recursión para crear un rango de números

Enlaza al desafío:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Even though for loops are better for creating an array of numbers, the purpose of this lesson is to teach you how to reuse the output of a function as its own input. Sometimes, recursion can be used to write code that would be more difficult to read and understand if written as a loop.

// recursive function
function countup(n) {
  let currentCount = n - 1; // count for current recursion
  let isLessThanOne = n < 1; // current count == 0

  if (isLessThanOne){
    return []; // end recursion when (n) == 0
  }
  let previousArray = countup(currentCount); // get array from last output
  let currentArray = [...previousArray]; // use last output as new array
  currentArray.push(n); // add new number to new array
  return currentArray; //  use array for next input
}
1 Like

Careful, missing a brace here.

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