Home > Enterprise >  Why is JavaScript allows it to do mathematical operations with a string type number?
Why is JavaScript allows it to do mathematical operations with a string type number?

Time:04-08

const num1 = 10;
const num2 = "10";

console.log(num1 * num2); // Output: 100
console.log(num2 * num2); // Output: 100

CodePudding user response:

Javascript has a feature called type coercion that allows values of one type to be implicitly converted into a type that is acceptable for an operation.

In "10" * 10, JS knows that multiplication with a string and number does not make sense, so it automatically converts the string into a number.

(However, in "10" 10, JS sees as a string concatenation operation and produces "1010".)

  • Related