Movatterモバイル変換


[0]ホーム

URL:


  1. Glossary
  2. Type coercion

Type coercion

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).Type conversion is similar totype coercion because they both convert values from one data type to another with one key difference —type coercion is implicit whereastype conversion can be either implicitor explicit.

Examples

js
const value1 = "5";const value2 = 9;let sum = value1 + value2;console.log(sum);

In the above example, JavaScript hascoerced the9 from a number into a string and then concatenated the two values together, resulting in a string of59. JavaScript had a choice between a string or a number and decided to use a string.

The compiler could have coerced the5 into a number and returned a sum of14, but it did not. To return this result, you'd have to explicitly convert the5 to a number using theNumber() method:

js
sum = Number(value1) + value2;

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp