i_made_that
i_made_that

Reputation: 947

Javascript -> how to recursively add an array of numbers?

I can't seem to figure out what's wrong with this code -> keeps throwing a "Maximum call stack size exceeded" error.

function arrayIntSum(array) {
    if (array === []){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

Upvotes: 0

Views: 1154

Answers (3)

The Mighty Programmer
The Mighty Programmer

Reputation: 1252

You should check by this way : a.length==0

you compared a with [] , being a '[]' literal, it has different memory space. and a has different memory space. So they are never equal. so recursion cross its limit

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

function arrayIntSum(array) {
    if (array.length === 0){
        return 0;
    }
    else return array.shift() + arrayIntSum(array); 
} 

Upvotes: 2

SLaks
SLaks

Reputation: 887451

Javascript objects are compared by reference.

[] creates a new array instance, which will will never equal your variable.

You want to check the length.

Upvotes: 9

Related Questions