can someone please explain it to me how does this function return ['y','e','s'] instead of just the string 'yes' ???? the value of num first will be 8 then else condition will work then num will be [5,6,7] and again the else condition will work then num finally becomes an empty array [] which will fullfill the if condition then it should return 'yes' but it doesn't!?
function ABC(num, ...rest) {
if (num < 5) {
return 'yes';
} else {
return [...ABC(rest)];
}
};
console.log(ABC(8, 5, 6, 7));
If you add a few console.log
it becomes clearer :
function ABC(num, ...rest) {
console.log(`num=`, num, ", rest=", rest)
if (num < 5) {
console.log(`returning 'yes'`)
return 'yes';
} else {
console.log(`returning [...ABC(${rest})]`)
return [...ABC(rest)];
}
};
console.log(ABC(8, 5, 6, 7));
So it goes into the else
and returns [...ABC([5, 6, 7])]
. There is only one argument, an array. So at run 2:
[5, 6, 7] < 5
? False. So it goes in the else
again. It returns [...ABC([])]
.
[] < 5
? True, oddly enough. So ABC([])
returns 'yes'
.
But then this 'yes'
is being returned into the previous function call, that is, [...ABC([])]
, which becomes [...'yes']
, which is ['y', 'e', 's']
.