Can anyone explain why this code concatenates rather than adds the numerical values?

Brandon Hernandez :

So, to start off, I know this code is messy, please bear with me, but can anyone explain why this keeps concatenating the entered information rather than adding the numerical values after being passed through parseInt()?

var sol = 0;
var n = 0;

while(n !== null)
{

parseInt(n = prompt("Please enter a number to be added onto stack"));
  if(n != null || n != NaN)
  {
    sol = parseInt(sol);
    sol += n;
  }

}
console.log(sol);
Alex Wayne :

prompt() returns a string.

parseInt() accepts a string and returns a number.

You aren't doing anything with the return value of the first parseInt. This means n is a string. So when you do sol += n you are adding a string and number together, and javascript assumes that you meant to concatenate strings together, since math with a string and number doesn't make any sense.

You probably meant to do:

n = parseInt(prompt("Please enter a number to be added onto stack"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11714&siteId=1