Tell us what’s happening:
Describe your issue in detail here.
I couldn’t understand how this code works.
**Your code so far**
// Only change code below this line
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
// Only change code above this line
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36
I know how the push statement work. I need to know how it pushes the value inside this code.
The output of this code will be : [1, 2, 3, 4, 5]. I need to know how it pushes the value 1 first and not 5.
The key really is that the code is executed in the order it is written. Where do you think adding some console.log statements might help you see what’s going on?
this function executes recursively each time by checking against a condition (n-1) is satisfied. each time (n-1) is true, the value of n is returned. in this case. countup of 5 i.e countup(5), n =5. at first 5 < 1, hence to the array countArray, it pushes n (5), then reduces n by one, that’s (5-1 = 4), then does the same process for n = 4. The same process of pushing 4 to the array happens then n is reduced by 1 it becomes 3. Each time n is returned while being reduced by 1 until when n < 1.,- no array is returned . Each pushed element is always placed at index 0, hence the result becomes [1,2,3,4,5]