2

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.

1
  • Because user enter a string and your number will be converted to string. Try enter "18" and you'll see "182". Check parseInt() on MDN. Commented Oct 26, 2014 at 17:56

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Instead of showing a correct answer, you could better describe what was going wrong in the code used by the person who asked the question.
All you would need to do to make this better is give a nod to the comment from @adrianorepetti
0

Try

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.