-1

hello! I'm trying to add numbers from an array. I went with the .reduce method, however it's not working. It keeps giving me a result of 0. I console logged the array, and indeed the values are there. Why isn't it doing the addition then?

        const cubitMeters =
          (parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000
        totalW.push(cubitMeters)
        const totalW = []
        const sum = totalW.reduce((a, b) => a + b, 0)

        console.log('sum: ' + sum)
        console.log(totalW)

and here's screenshot of console.log results enter image description here

Mateusz Szumilo
  • 109
  • 2
  • 7
  • 1
    This ***cannot*** be the code you use. 1. You declare `const totalW = []` immediately before trying to reduce it. At that point the array should be empty. 2. However, you are calling `totalW.push()` *before the declaration*. That should lead to a ReferenceError due to [the temporal dead zone](https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone). – VLAZ Nov 07 '22 at 17:46
  • Hey Looks like you need to move the array declaration to top. Anthen perform the push operation – Nishanth Nov 07 '22 at 17:46
  • 1
    Looking at the log, I can clearly see the effects of [console.log() shows the changed value of a variable before the value actually changes](https://stackoverflow.com/q/11284663) - you've logged the array *which was empty at the time of logging*, then you've reduced its value *correctly* to zero, then you've added two items in it *afterwards*. When you've expanded the array in the console, it was evaluated and it shows the two items in it but the initial log *before* you expanded it in the console is just `[]` thus it was empty. – VLAZ Nov 07 '22 at 17:49
  • What kind of compiler are you using that is not throwing any error? – Ali Mustafa Nov 07 '22 at 17:50
  • 1
    @AliMustafa my guess is that this isn't the real code. OP just hasn't provided a [mcve]. – VLAZ Nov 07 '22 at 17:51

1 Answers1

1

Looks like you need to move the array declaration to top. And then perform the push operation.

const totalW = []
const cubitMeters =
  (parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000
totalW.push(cubitMeters)
const sum = totalW.reduce((a, b) => a + b)
console.log('sum: ' + sum)
console.log(totalW)
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Nishanth
  • 304
  • 3
  • 12