简体   繁体   中英

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?

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, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM