0

Here is my code:

var health = prompt("Type in health");
var attack = prompt("Type in attack");
var defense = prompt ("Type in defense");
function calculatestats(health,attack,defense){
    return health/4 + attack + defense
}
alert (calculatestats(health,attack,defense));

I want to make it output "3" when I type in 4, 1, and 1. The javascript is adding the characters, "1", "1", and "1". I want to add it Mathematically, and make it output 3, not 111. Thank you.

Ardent
  • 53
  • 7
  • convert the strings to numbers.... – epascarello Dec 19 '17 at 14:31
  • use parseInt https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt or parseFloat if you want to include floating point numbers. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat – Andrew Lohr Dec 19 '17 at 14:34

1 Answers1

3

The prompt() returns a string. You have to do explicit type conversion using + or parseInt:

function calculatestats(health,attack,defense){
  return +health/4 + +attack + +defense;
}

Better way:

function calculatestats(health,attack,defense){
  return parseInt(health)/4 + parseInt(attack) + parseInt(defense);
}
Soolie
  • 1,812
  • 9
  • 21