Why is my function concatenating instead of adding the numbers?

8

I'm learning JavaScript and I'm breaking my head with this code I created. Why is my function concatenating instead of adding up the numbers I store in variables?

<!DOCTYPE html>
<html>
<head>
    <title>Aula 05 Java Script</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        var num1,num2;

        num1 = prompt("Digite um número ","");
        num2 = prompt("Digite outro número para somar ","");

        function soma(){
            var res;
            res=num1+num2;
            alert("Reultado da Operação "+ res);
        }

        soma();

    </script>
</head>
<body>
</body>
</html>
    
asked by anonymous 30.04.2016 / 21:55

2 answers

7

This is because the return from prompt() is always a string . Then the addition will do the concatenation of both. If you want to add the numbers you need to convert the variable to a numeric type, this happens with parseInt() , for example.

num1 = prompt("Digite um número ","");
num2 = prompt("Digite outro número para somar ","");

function soma(){
    var res = parseInt(num1) + parseInt(num2);
    alert("Reultado da Operação "+ res);
}

soma();

Or if you prefer that the variables are already numeric:

    num1 = parseInt(prompt("Digite um número ",""));
    num2 = parseInt(prompt("Digite outro número para somar ",""));

    function soma(){
        var res = num1 + num2;
        alert("Reultado da Operação "+ res);
    }

    soma();

You can also use ParseFloat() if you want the number allow numbers with decimal part.

Note that if the conversion is not possible, after all the person can type a text, it may not give the expected result since the value will probably be 0, or something that it can convert, but not well what was typed.

    
30.04.2016 / 21:58
8

The problem is that the return of prompt is a string ( take a look here ).

So, if you convert these strings into numbers your code will already work.

For example, using Number :

var res = Number(num1) + Number(num2);

jsFiddle: link

Note:

  • different ways to convert strings to Numbers

In JavaScript there is parseInt that converts a string in an integer, removing the decimal part without rounding. You can also use parseFloat , or Number . All convert strings into numbers.

    
30.04.2016 / 21:59