How and why JavaScript type coercion works?

Viewed 66

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?

2 Answers

It's simply because what you wrote in the console.log command outputs a string, therefore when you use 'The number is ' + x what you're doing is essentially string concatenation.

On the other hand if you use console.log(x) you'd get an int response.

You can check this here:

var x = 5;

console.log("The number is " + x);
console.log(typeof ("The number is " + x));

console.log(x);
console.log(typeof x);

console.log(x + x);
console.log(typeof (x + x));

You can check more on this in MDN's Docs

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

Related