Search code examples
javascriptparseint

Save and parseInt user input in one line of code? (Javascript)


Here's my code:

function add() {
  var num1 = prompt("Enter 1st number")
  var num2 = prompt("Enter 2nd number")
  parseInt(num1);
  parseInt(num2);
  var result = num1 + num2;
  alert(result);
}
add();

I'm trying to build a simple addition calculator. parseInt wasn't working and an answer here said to declare the variable like var num1 = parseInt(num1);. However since I'm only getting "num1" through user input (var num1 = prompt..."), not sure how to store it as integer, or parseInt, in the same line. Any advice? Thanks.


Solution

  • All you have here are standalone, unused expressions:

    parseInt(num1);
    parseInt(num2);
    

    Those evaluate to numbers, but you don't use them, so they're useless. Either assign them to variables, eg

    const actualNum1 = parseInt(num1);
    const actualNum2 = parseInt(num2);
    

    and then use those variables, or just wrap the prompt in parseInt:

    var num1 = parseInt(prompt("Enter 1st number"))
    var num2 = parseInt(prompt("Enter 2nd number"))
    

    Unless you're intending to only accept integers, consider using Number instead:

    var num1 = Number(prompt("Enter 1st number"))
    var num2 = Number(prompt("Enter 2nd number"))