let's see two ways to declare an empty array
const a = [];
const b = new Array();
console.log(a) // []
console.log(b) // []
So you get the same output, now with your question, [] is a way to declare an array, and javascript knows it.
Then if you have the function:
function countup(n) {
if (n < 1) {
// return [];
return new Array();
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
Maybe this way you can figure it out what is happening, you are creating and returning a new empty array, to end the clarification, let's change the function call:
// console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
const newArrayUpToFive = countup(5);
console.log(newArrayUpToFive); // [ 1, 2, 3, 4, 5 ]
// Now the empty array
const newArrayEmpty = countup(0) // the return value is new Array()
// const newArrayEmpty = new Array(); // It is like this sentence
console.log(newArrayEmpty) // []
Step by step:
console.log(countup(2));
// The function does (as n = 2)
const countArray = countup(1) // 2 - 1, Let's say this is the 'A' call
// The function has to wait for the countup return statement
// Now countup is called again with n = 1, and we have
const countArray = countup(0) // 1 - 1, 'B' call
// Again, the function has to wait for the countup return statement
// Finally countup is called n = 0 and the if condition
// is true, so:
return [];
// B call gets the value [], in 'B' call the value of n was 1
const countArray = [];
countArray.push[1]
return countArray; // returns [1]
// A call gets the value [1], in 'A' call the value of n was 2
const countArray = [1];
countArray.push(2);
return countArray; // returns [1, 2]
So at the end, console.log is called with the value [1, 2].
n===1. Then, whencountup(0)is called (ascountup(1-1), an empty array is returned. In that instant, on the same line, the empty array is assigned to the variablecountArray. from there1is pushed, and the array[1]is returned, assigned to thecountArray1 level back up the tree, and you continue recursing back up to your starting number.