Path: csiph.com!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: sum array Date: Sun, 12 Nov 2017 01:20:22 +0000 Organization: A noiseless patient Spider Lines: 19 Message-ID: <878tfcwaw9.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="6990cf73bed5c4f34de9a73f4d41615b"; logging-data="32651"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/Z1YjiDdK69oU8NTdNp/uyP8zzvF67bDw=" Cancel-Lock: sha1:loEjZJWqhqSEpyXO5N1emw8b6KI= sha1:mLuuxOYfmsTPzHIphTqb0/XfnJM= X-BSB-Auth: 1.74f769a6410fd1aeed99.20171112012022GMT.878tfcwaw9.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:34311 Andrew Poulos writes: > To sum the integer elements in an array I'm using > > var sum = arr.reduce(function(a, b) { > return a + b; > }); > > which is fine. When I pass it > var arr = [,0, 1, -1, 3,, null]; > I get the correct answer though I'm expecting it to error. Why doesn't > it throw an error or at least not the right answer? First, reduce only considers the elements that are present in the array, and second, null is converted to +0 before the addition (non-string operands of + are converted to number using the the ToNumber abstract operation). -- Ben.