-2

I'm trying to write a code which calculate the total of an array length of 3. Each 3 integers are from prompt.

Right now my code is like the following:

var num1 = prompt("First number");
var num2 = prompt("Second number");
var num3 = prompt("Third number");

var new_array = [num1, num2, num3]

function sum_three(new_array)
    {
        return new_array[0] + new_array[1] + new_array[2];
    }

document.write(sum_three(new_array));

However when I see the result it seems that this

return new_array[0] + new_array[1] + new_array[2];

part does not calculate, it just concatenate the numbers. How do I make work?

kayak
  • 440
  • 3
  • 7
  • 19
  • 3
    Parse your numbers to an integer. – Nick Dec 18 '17 at 08:05
  • 1
    Okay I just added lines like var num1_int = parseInt(num1); var num2_int = parseInt(num2); var num3_int = parseInt(num3); and it worked. But do you know is there any other way which I can reduce the code? I think they're getting too long. – kayak Dec 18 '17 at 08:15
  • Use reduce for the summing, and Number() to get numbers out of your strings. `let res = arr.reduce((a, b) => a + Number(b), 0);`. Your whole code: `let res = new Array(3).fill().reduce((a,b) => a + Number(prompt("Enter number")), 0); ` – baao Dec 18 '17 at 09:27

2 Answers2

1

Inputs entered by your keyboard are strings. If you use 'addition' + on strings, you concatenate them. You have to convert (parse) the numbers contained in your string to an actual javascript number.

One simple way of doing it is by adding a + in front of each string variable. It will try it best to 'interpret' your strings as numbers

return +new_array[0] + +new_array[1] + +new_array[2];

Actually, the correct technical term is 'coercion', thanks @NeilDocherty, more info here https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md)

Simple example exhibiting the behavior :

console.log("3" + "5"); // outputs 35
console.log(+"3" + +"5"); // outputs 8

You can also use parseInt, as you already did.

There are differences between the two, see for example this post : parseInt vs unary plus - when to use which

In particular, parseInt will return NaN for an empty string whilst + will coerce it as 0 .

Pac0
  • 21,465
  • 8
  • 65
  • 74
0

A more modern solution would be to use the Array.prototype.reduce method.

I find this more readable, but if you are going to support browsers older than IE9, then you will need to polyfill it in.

var new_array = [prompt("First number"), prompt("Second number"), prompt("Third number")];

function array_sum(accumulator, currentValue) {
  return parseFloat(accumulator.toString()) + parseFloat(currentValue.toString());
}

function sum_three(arr) {
  return arr.reduce(array_sum);
}
document.write(sum_three(new_array));
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28