Why we assign the recursive call to the array variable?

/* why are we assigning the recursive call in numbers variable, can’t we just call the recursive fn and push… let numbers = recursive call*/

function rangeOfNumbers(startNum, endNum) {

if(startNum>endNum)  

{

  return [];

}

else

{

 let numbers = rangeOfNumbers(startNum,endNum-1);    

/*  why are we assigning the recursive call in numbers variable, can't we just call the recursive fn and push.*/

  numbers.push(endNum);

  return numbers;

}

};

console.log(rangeOfNumbers(6,9))

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 (’).

No, you need numbers because the push method does not return the resulting array (other languages do, but no t JavaScript). If you write

return rangeOfNumbers(startNum, endNum-1).push(endNum)

you’re not returning a new array.

const r = [2, 8].push(6)
console.log(r)

will print 3.

1 Like

Push returns the new length of the array, I believe

1 Like

I mean that if i call the recursive function(without assigning it to the numbers variable) and then push the values in the array and then if i return the array (return numbers), will it not work ?

If you never save the output of the recurse call to a variable, then there is no array to push onto. The scope of each function call is separate.

Thank you , I just joined , i didn’t know that :smiley:

1 Like

I’m not sure but do you mean like this?

const numbers = rangeOfNumbers(startNum, endNum-1).push(endNum)
return numbers

This won’t work because numbers won’t be an array.

const arr = [10, 20, 30]
arr.push(40)   //arr is mutated and it is now [10, 20, 30, 40]

const nums = [10, 20, 30].push(40) //nums is 4, the number of elements in nums

Thanks, got it.:smiley:

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