When I tried to run the following piece of code:
function flatten(a) {
return [].slice.call(arguments).reduce(function(acc, val) {
return acc.concat(Array.isArray(val) ? flatten.call(null, val) : val);
}, []);
}
I got the following error:
Uncaught RangeError: Maximum call stack size exceeded
But if I used flatten.apply
instead of flatten.call
, it works perfectly. (deep flattens the input array).
In addition to this link1 and link2, I read few other blogs and articles to understand why it behaves so. I either couldn't find the answer or I must have overlooked it. (pardon my soar eyes if in latter case)
Of course, the fundamental difference between these 2 is:
apply - requires the optional parameter be an array
call - requires the optional parameters be listed explicitly
Usually, a function may take any type of parameters - primitives and non-primitives. So, my questions are:
Could one of the optional parameters to the call method be of type
Array
or other non-primitive types?Why does the above code exceeds call stack, when
call
is used?
Edit: Since there were 2 call
methods used, my description was ambiguous. I made changes to clarify.