I was making a small recursion function to sum elements of array.
let sum = arr => {
if (arr == []) return 0;
return arr.shift() + sum(arr);
}
Using if (arr == []) statement, terminal says "Maximum call stack size exceeded".
After I change statement to if (arr.length == 0) everything works fine.
Why first condition doesn’t work?
>Solution :
arr == [] will be always false, since that’s 2 different arrays, since arrays are objects in JS and objects are compared by reference. Only arr === arr /* or any variable assigned this array */ could be true.
From MDN:
Loose equality using ==
Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions). The behavior for performing loose equality using == is as follows:
If the operands have the same type, they are compared as follows:
Object: return true only if both operands reference the same object.
Since arr == [] is always false you would never return 0 and the recursion runs indefinitely thus overflowing the call stack.
You could possibly simplify the code with the ternary operator:
let sum = arr => arr.length ? arr.shift() + sum(arr) : 0;
console.log(sum([0, 1, 2, 3, 4, 5, 6]));