arunwebber
arunwebber

Reputation: 91

Java script addition of numbers with giving wrong answer

I am working with a simple java script code which goes here

<script>
var x=prompt("Enter a number");
var n=x+2;
alert(n);
</scrip>

This code will throws a prompt If i enter 2 in the prompt.I am expecting output as 4,But it is generating 22 in alert. What mistake is happening here.

Upvotes: 2

Views: 138

Answers (4)

friedi
friedi

Reputation: 4360

Here an alternative way of doing this:

var x = +prompt("Enter a number");
var n = x+2;
alert(n);

The plus sign (in front of prompt) converts the string to a number.

Upvotes: 0

Patricia
Patricia

Reputation: 2865

Try

<script>
var x = prompt("Enter a number");
var n = parseInt(x)+2;
alert(n);
</script>

Upvotes: 0

sbrbot
sbrbot

Reputation: 6469

<script>
var x=prompt("Enter a number");
var n=parseInt(x)+2;
alert(n);
</scrip>

Upvotes: 0

Andre Pena
Andre Pena

Reputation: 59436

Yes.

 var n;
 if(!isNaN(x)) {
    n = parseInt(x) + 2; // make sure x is always a number here
 }

This is because the prompt function will return an String, not a number.

String + Number = String

Upvotes: 4

Related Questions