Recursion Countdown Challenge

Hi, so i have understood how the recursion works but i couldn’t wrap my head around why we use const before arr. Help please :smiley:

function countdown(n){
  if(n<1){
    return [];
  }
  else{
    const arr = countdown(n-1);
    arr.unshift(n);
    return arr;
  }
}

The general rule is to always declare a variable with const unless you need to mutate it, then use let. The trick here is that doing an unshift on the array is not mutating the variable itself, but rather the array the variable is pointing to, so you can use const for arrays and still change the array itself. Now if you were going to assign the variable arr a completely different array then you would have to use let.

1 Like

Thanks for the explanation :relaxed:

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