Type coercion
Examples
const
value1 =
"5"
;
const
value2 =
9
;
let
sum =
value1 +
value2;
console.
log
(
sum)
;
In the above example, JavaScript has coerced
the 9
from a number into a string and then concatenated the two values together, resulting in a string of 59
. JavaScript had a choice between a string or a number and decided to use a string.
The compiler could have coerced the 5
into a number and returned a sum of 14
, but it did not. To return this result, you'd have to explicitly convert the 5
to a number using the
Number()
method:
sum =
Number
(
value1)
+
value2;
See also
- Type conversion (Wikipedia)
- Glossary