In prompt
the user's response is a string. Even if the response is a number, it comes back as a string. So I did some addition in the console:
var numberOfCats = prompt("How many cats?");
var tooManyCats = numberOfCats + 1;
If I type number 3
in the prompt
box and then check tooManyCats
, the result is: 31
. Because Javascript can't do math using a string and a number. So it adds the number 1
right beside it.
But for this example, for some reason it doesn't mess up the code. Here I made a age calculator in the console.
var age = prompt("What is your age?")
var days = age * 365.25; //.25 is for the leap years
alert(age + " years is roughly " + days + " days");
If I type 20
in the prompt
box, it alerts me: 20 years is roughly 7305 days
I can't understand why the second one works without any issues. Is it because of Javascript seeing the string and number in it's own unique way or is there some reason behind it?