Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Maximum call stack size exceeded in recursion function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading