Java Reference
In-Depth Information
Type Coercion
Type coercion is the process of converting the type of a value in the background to try and
make an operation work. For example, if you try to multiply a string and a number togeth-
er, JavaScript will attempt to coerce the string into a number:
"2" * 8;
<< 16
This may seem useful, but the process is not always logical or consistent, causing a lot of
confusion. For example, if you try to add a string and a number together, JavaScript will
convert the number to a string and then concatenate the two strings together:
"2" + 8;
<< "28"
This can make it difficult to spot type errors in your code, so you should always try to be
very explicit about the types of values you are working with.
Converting Between Strings and Numbers
We can convert numbers to strings and vice versa using a variety of methods.
Converting Strings to Numbers
To covert a string into a number we can multiply a numerical string by 1 , which will con-
vert it into a number because of type coercion:
answer = "5" * 1;
<< 5
typeof answer;
<< "number"
Another neat way of converting a string to an integer is to simply place a + symbol in front
of it:
Search WWH ::




Custom Search