Cannot figure out what error message means

Cannot figure out what error message means
0.0 0

#1

Hi, I’m trying to solve “Sum All Primes” challenge. I decided to use Sieve of Eratosthenes as part of my solution. Here is the Wikipedia article about this method.
I’m not asking if my implementation is good, if it isn’t I’ll figure it out myself. Question is why I’m getting “TypeError: acc.push is not a function” message, when acc is passed as empty array.
Code:


function sieveOfE(arr, acc) {
    if (arr === []) {
        return acc;
    }
    return sieveOfE(arr.slice(1)
                       .filter(function (e) {
                                   return e % arr[0] !== 0;
                               }),
                        acc.push(arr[0]));
}

console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], []));

Thanx in advance.


#2

What is acc? It’s not what you expect, so log it immediately.


#3

acc is accumulator. It’s kind of optimization to recursive calls. Problem is that I pass the initial value as empty array, and get error that array has not method “push()”? That confuses me.


#4

I put console.log(acc) before recursive call and output was [], as should be.


#5

Because arr === [] will always be false. You can’t compare objects with == or ===

Use if (arr.length === 0)


#6

Thank you. I used to do some python earlier, arr == [] is totally ok in py world. But, error is still the same “TypeError: acc.push is not a function” after i changed my condition as you suggested.


#7

Array.push() returns the length of the array.


#8

Thank you. Good point, i used .concat instead and get rid of error.
Now just need to fix my implementation. :wink:


#9

well yeah, but your pasted code has a syntax error — two closing brackets.


#10

I got rid of those, works like a charm with concat instead of push. Thank you anyway.