Why is my function concatenating instead of summing the numbers?

Asked

Viewed 6,643 times

10

I am learning Javascript and I am breaking my head with this code that I created. Why is my function concatenating instead of summing the numbers I store in the 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>

2 answers

10


This is because the function return prompt() is always a string. Then the addition will concatenate both. If you want to sum the numbers you need to convert the variable to a numeric type, this is done 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 numerical:

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();

I put in the Github for future reference.

It is also possible to use the ParseFloat() if you want the number to 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 he can convert, but not quite what was typed.

  • 1

    We responded in the same minute :) +1

  • Thank you so much! Now besides solving I understand the reason! .

10

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

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

For example, using the Number:

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

jsFiddle: https://jsfiddle.net/2d1otn4a/


Note:

  • different ways to convert strings to Numbers

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.