Code shows a recursive function that takes a number, say n=5, and returns an array counting down from n to 1 i.e [5,4,3,2,1].
My confusion lies right before we push the numbers/values of n to countArray. My understanding is that countup(n - 1), will generate numbers (say n=5) 5,4,3,2,1...but I don't understand where/how they are stored. I would have thought n would end up as its last defined value, n=1, or a blank array. But that's not true and they are somehow all pushed into an array that in my understanding was never created/defined prior to pushing into it. So those two lines with comments are the two I need help understanding.
tl;dr: (1) how are the values 5->1 stored without overwriting to the final value 1, prior to being pushed into the array? (2) Where/how was countArray defined as an array before we push into it;
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1); //the storing of 5,4,3,2,1 I don't understand
countArray.push(n); //I don't understand when countArray was defined as an array
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
edit: this post's title probably need changing to array rather than variable or etc.