So what the recursiveArrayPrint function does, is that it creates a variable and returns a function that has closure over this variable. I think you get this part. The part that might confuse you, is that when you encounter an array, you call the recursiveArrayPrint function again, which will only create a new variable and return a new function that has closure over this variable, but this is in an entirely different scope.
It might make more sense to look at it this way.
var array = [1, 2, [3, 4], 5, [6, [7, 8]]]; // --> 1,2,3,4,5,6,7,8
function recursiveArrayPrint(array) {
let resultado = []
return function iterator() {
for (let i = 0; array.length > i; i++) {
if (Array.isArray(array[i])) {
// This is where a new closure is created, but with reference to another variable
let resultado1 = []
return function iterator1() {
for (let i = 0; array.length > i; i++) {
if (Array.isArray(array[i])) {
// This is where a new closure is created, but with reference to another variable
}
return resultado1
}
}
} else {
console.log(array[i])
resultado.push(array[i])
}
}
return resultado
}
}
const test = recursiveArrayPrint(array);
console.log('test: ',test())
I think what you intend to do is something more like this.
var array = [1, 2, [3, 4], 5, [6, [7, 8]]]; // --> 1,2,3,4,5,6,7,8
function recursiveArrayPrint() {
let resultado = []
return function iterator(array) {
for (let i = 0; array.length > i; i++) {
if (Array.isArray(array[i])) {
iterator(array[i])
} else {
console.log(array[i])
resultado.push(array[i])
}
}
return resultado
}
}
const test = recursiveArrayPrint();
console.log('test: ',test(array))
resultado.push(...recursiveArrayPrint(array[i])());where you call it inside the loopiteratorrecursively (and give it a parameter for that), notrecursiveArrayPrint.