Hi, let’s break this down bit by bit.
We first start and see the ternary operation in the form of (boolean expression) ? (code to execute if true) : (code to execute if false);
In this case, if the given inputs startNum and endNum are equal, then we return an array with one item: startNum
if the two inputs are not equal, then we call the function rangeOfNumbers (which is itself) again.
So in terms of if/else, the code can be rewritten as:
function rangeOfNumbers(startN,endN) {
if (startN===endN)
return [startN]
else
return rangeOfNumbers(startN,endN-1).concat(endN);
now let’s look at the function calling itself, or recursion. It calls rangeOfNumbers with the second input, endNum decremented by 1, which we established returns an array, and attaches to it via .concat() method the endNum itself.
This means this call to rangeOfNumbers will continue to call itself while decrementing endNum, attaching one number to the back, until the two inputs are equal.
It is easier to visualize with pencil, paper, and a testcase:
Testcase of rangeOfNumbers(1,5)
the two inputs are not equal, executing rangeOfNumbers(1,4).concat(5);
the two inputs are not equal, executing rangeOfNumbers(1,3).concat(4);
the two inputs are not equal, executing rangeOfNumbers(1,2).concat(3);
the two inputs are not equal, executing rangeOfNumbers(1,1).concat(2);
the two inputs are equal, returning [1]
code from step 4 is resolved: [1].concat(2) which is [1,2]
code from step 3 is resolved: [1,2].concat(3) which is [1,2,3]
code from step 2 is resolved: [1,2,3].concat(4) which is [1,2,3,4]
code from step 1 is resolved: [1,2,3,4].concat(5) which is [1,2,3,4,5]
The end return is therefore an array of a range of numbers between startNum and endNum
And just to add - do not get frustrated if you struggle with recursion. It is very normal, because it can be a mind-bendingly bizarre idea when you are starting out. Just keep at it. It actually a long time before I wrapped my head around it.
My advice also is to check out blogs and youtube videos on recursion. As twotani shows, there is something visual about how recursion works, especially if you start understanding how the call stack works. I would watch a bunch of different videos and I think that gradually the concepts will start to sink in.