2

I'm wanting to print number + 1 in the console log but instead of adding the numbers together, it concatenates them. What am I doing wrong? For instance, if the user inputs 7, instead of getting 8, it will print 17.

let number = prompt('what is your favorite number')
if(number == 42){
  console.log("Yay! That's my favorite too!")
} else if (number < 42){
  console.log("Eh, that's OK but " + (1 + number) + " would have been better")
} else{
  console.log("LAME. That number is too large!")
}


console.log()

If a user inputs a number less than 42, it should add 1 to the entered number and print that number. However, the current code is concatenating 1 to the number.

3
  • 1
    This is because javascript is a dynamic typed language, it can convert numbers to strings based on the context, try number*1, this is clearly a number operation so javascript will treat number as a number and not as a string. Commented May 8, 2019 at 14:07
  • 1
    parseInt(number) will solve your problem Commented May 8, 2019 at 14:07
  • Possible duplicate of Sum of two numbers with prompt Commented May 8, 2019 at 14:08

4 Answers 4

1

prompt returns a string... you need to convert it to a number, for example with

number = +number;

before using it as a number

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

Comments

1

You can use as it will consider it a string while performing arithmatic operations

number = Number(number)

You will get more details about this wrapper object here.

Comments

0

That is because prompt returns a string. So if you enter 21 for example and add 1 the result will be 211.

You need to convert number to a number right after prompt like:

number = parseInt(number);

Comments

0

It's because the value returned from executing prompt is a string rather than a number. You need to parse the string into a number using parseInt[1], or if you're allowing floats parseFloat[2].

For example:

let response = prompt('what is your favorite number')
let number = parseInt(response, 10) // Convert response into a string
if(number == 42){
  console.log("Yay! That's my favorite too!")
} else if (number < 42){
  console.log("Eh, that's OK but " + (1 + number) + " would have been better")
} else{
  console.log("LAME. That number is too large!")
}


console.log()

References

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

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.