Basic JavaScript: Use Recursion to Create a Range of Numbers - const keyword

I have a very specific question in regards to how the const declaration of our result array plays into solving this. The const declaration isn’t needed here but an earlier example of a similar problem also used a const declaration and it works fine.

function rangeOfNumbers(startNum, endNum) {
  if(startNum === endNum) {
    return [startNum];
  } else {
    const result = rangeOfNumbers(startNum+1, endNum);
    result.unshift(startNum);
    return result;
  }
};

The const declaration creates a read-only reference to a value but the value is not immutable. Now when we start working down our call-stack each const result declaration will be set to the value of what is returned from rangeOfNumbers. Does this work because each function has it’s own “version” of const result?

Exactly. The variables in each function call are in their own separate scope.

1 Like

1/2 month after graduating with a CS degree I’m asking questions about variables in different function calls, brother almighty.

Thank you Jeremy!

1 Like

Recursion is a tricky thing to keep straight

1 Like