11.11 studio: More Functions bonus question

So, I successfully did the bonus part of the More Functions studio where I was tasked with rewriting my number array sorter with recursion. However, with recursion I was unable to initialize the empty array that the function returns inside the function. I had to initialize it as a global variable.

Just curious, is it possible at all to initialize the empty array inside the function while using recursion? Here’s what I have with the empty array initialized outside the function.

let sortedArray = [];

function numberSort(arr){
if (arr.length === 0) {
return sortedArray;
} else {
return numberSort(arr);

Yes I have done so. I have mine initialized at the beginning of my function code block. IDK if it’d work for yours but mine is part of the function & initialized prior to if statement. It won’t be a global variable then. I’d try that!

Just so you know, I tried it like the other guy said, but I couldn’t get it to work without it being globally scoped. I’m guessing it’s because each time the function calls itself, it resets the value of the blank array that you initialized, and so it returns an empty array after the last call. I’m sure there’s a way to do it, but I couldn’t figure it out.

This is what I did & I am not having issues with it. Possibly I am not understand what is the crux of the issue:

One method of initializing and then using a data structure, like an array, within a recursive function is to use default parameters. You can read about default parameters here.

Here’s how it’d work:

You define the default parameter along with your regular parameters by assigning it the default value of your choosing, in this case an array literal. For example:

function recursion(array, returnArray = [ ]) {
// code goes here

Because you defined a default value, when you first call your function, you don’t need to provide an argument there, as the default value handles it for you.

You can then modify that default parameter and maintain its changing state across recursive calls, so long as you explicitly include that parameter in subsequent calls. For example:

// somewhere in the function, after modifying returnArray
return recursion(array, returnArray)

Hope that makes sense and helps!

1 Like