Reputation: 91
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
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
Reputation: 2865
Try
<script>
var x = prompt("Enter a number");
var n = parseInt(x)+2;
alert(n);
</script>
Upvotes: 0
Reputation: 6469
<script>
var x=prompt("Enter a number");
var n=parseInt(x)+2;
alert(n);
</scrip>
Upvotes: 0
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