3

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?

5 Answers5

5

It works because unlike +, * converts its operands to numbers if necessary before doing the multiplication, so * expressions always result in a number value (even if that value is NaN) (or a BigInt if both operands are BigInts), whereas + may result in a number (or BigInt) or a string, depending on its operands. (In fact, + is the only one of the classic math operators that doesn't always result in a number or a BigInt; -, /, %, and * always do). So days is a number, since it's the result of * (on something other than BigInts).


About BigInts: The only time +, -, /, *, and % operator expressions result in BigInts is if both operands are BigInts, there is no implicit conversion. If only one of the operands is a BigInt, the operation throws a TypeError.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Javascript decides automatically if the input you entered is a string or a number. Sometimes its not correct and its up to you to change it. You can use Number() method to transform string into number. Or as mentioned by T.J. Crowder you can multiply string by 1 and you get a number (numberOfCats*1).

0

Your second entry is a multiplication (*). That can't be simply added as a string, so JS is responding with the answer to the multiplication you've entered. The first entry is addition (+), which treats the string as a concatenation rather than equation.

Carson
  • 864
  • 1
  • 6
  • 19
0

Javascript always concatenate with '+' operator if the input is in numeral. but with operators like *,/,% it always convert the string entered in numeral format to number.

5+'5'=55

5*'5' doesn't make any sense if Javascript teaches it as a string. Similarly for *,/,%.

shinjw
  • 3,329
  • 3
  • 21
  • 42
EhtU
  • 41
  • 4
0

In javascript "+" operator used for addition also "+" is overloaded as concatenation operator which is automatically decided based on the operands. If any of the operads is a string it will concatenated.

Biju Kalanjoor
  • 532
  • 1
  • 6
  • 12