Search code examples
javascriptarraystype-conversioncoercion

Sum the contents of a JavaScript array


Beginning JavaScript learner here...

I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 5 in the elementary exercises.

Write a program that asks the user for a number n and prints the sum of the numbers 1 to n... such that only multiples of 3 and 5 are considered.

Here is my code as it currently stands...

var myArray = [];
var mySum = 0;

var userNum = prompt("What is your number? "); {
    for (var i = userNum; i > 0; i--) {
        if (i % 5 === 0 || i % 3 === 0) {
            mySum += myArray.push(i);
        } 
    }
}
console.log(mySum);

This produces the result 28 which is not correct. When I comment out the mySum statement and print the array for the input of 17 I get [15, 12, 10, 9, 6, 3] which looks correct.

I would be interested in tips on why the mySum statement doesn't provide the expected result. I would also be interested in any tips to make the code more efficient. Many thanks!

Edit
For anyone interested, here's the code I settled on for being best for my purpose and current level:

var mySum = 0;

var userNum = prompt("What is your number? ");
for (var i = userNum; i > 0; i--) {
    if (i % 5 === 0 || i % 3 === 0) {
        mySum += +i; // type coercion with unary operator
    } 
}
console.log(mySum);

Thanks to everyone!


Solution

  • Since myArray.push(i) does not return the number you pushed but the current length of the array, your sum is not what you expect.

    Instead use mySum += i;

    or if you want to still use the array to later process/console.log the separate numbers:

     mySum += i; 
     myArray.push(i);
    

    or just myArray.push(i); and afterwards reduce the array:

    sum = myArray.reduce(function(a, b) {
      return a + b;
    });
    

    Here I also cast the string you get when you prompt to a number and remove the wrapping { } which are not necessary

    var myArray = [];
    var mySum = 0;
    
    var userNum = prompt("What is your number? "); 
    for (var i = +userNum; i > 0; i--) {
      if (i % 5 === 0 || i % 3 === 0) {
        mySum += i;
        myArray.push(i);
      } 
    }
    console.log(mySum,myArray);

    Alternative using reduce - it is likely overkill in your case but I include it for completeness' sake:

    var myArray = [];
    var mySum = 0;
    
    var userNum = prompt("What is your number? "); 
    for (var i = +userNum; i > 0; i--) {
      if (i % 5 === 0 || i % 3 === 0) {
        myArray.push(i);
      } 
    }
    mySum = myArray.reduce(function(a, b) {
      return a + b;
    });
    
    
    console.log(mySum, myArray);