Search code examples
javascriptstringtypestype-coercion

How and why JavaScript type coercion works?


var x = 5;

If I run console.log('The number is ' + x);

The output is The number is 5;

But my question is that why the number convert into string?


Solution

  • In type coercion, i.e comparing or calculating two operands of a different type, one of them will be converted to an equivalent type. The reason number is converted to string is because every number can be a string but the opposite can't always be true, so the type coercion always converts a number to a string