In fact, in a recursive function, it is crucial to have a stop condition.
But the problem is that when the array has zero size, it does not enter the if
, and the function does not find any return
. And in these cases, the function ends up returning undefined
.
Then you need to return something when the array is empty. In case, as you are mounting a string with the elements, just return an empty string:
function meuArrayRecursivo(arr) {
if (arr.length > 0) {
let el = arr[0];
arr.shift();
return `${el} ${meuArrayRecursivo(arr)}`;
}
return ''; // <--- aqui
};
console.log(meuArrayRecursivo([1, 2])); // 1 2
I also changed the code above to use a function
normal. The use of Arrow Function here does not bring any advantage - many people think it is the only way/a "better"/more "modern", etc., but in fact there are some differences (in the specific example there are no, but there are cases where there are, see the documentation for more details - this link is also interesting).
Detail that the method shift
, in addition to removing the first element of the array, also returns this element, then you could do so:
function meuArrayRecursivo(arr) {
if (arr.length > 0) {
return `${arr.shift()} ${meuArrayRecursivo(arr)}`;
}
return '';
};
console.log(meuArrayRecursivo([1, 2]));
Or so:
function meuArrayRecursivo(arr) {
return arr.length ? `${arr.shift()} ${meuArrayRecursivo(arr)}` : '';
};
console.log(meuArrayRecursivo([1, 2]));
Perfect! I still have a lot to improve... but it helped me a lot! =)
– Leandro Barbosa