Search code examples
javascriptstringnumberstypeof

Why does a number that is typeof string, multiplied by another number that is typeof string result in a number?


So I am running algorithms and have ran into a solution to a problem that I do not understand. I know string + string results in the two strings combined even if those strings are numbers of type string. What I do not understand is why multiplying a number that is type string by another number also type string results in a value that is type number. For example:

The result of "8" * "9" is 72 and type is number, but "8" + "9" gives "89" and is a string. This is shown in the following snippet:

console.log("8" * "9");
console.log("8" + "9");

Why or how does the multiplication symbol convert a string to a number?


Solution

  • It is because * is not defined for strings, i.e. there is no meaning (and definition) in multiplying a string by another string, so, it checks to see if the strings are numbers (where * is defined), and if they are, it multiplies them as numbers (if one isn't numeric, it outputs NaN, "Not a Number"). With addition however, + is defined for both numbers and strings, so when trying to add strings, it just adds strings rather than check whether their values are numerical, because then it will be ambiguous as to what you want to add, the strings or the numbers.