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-
"2" * 8;
This may seem useful, but the process is not always logical or consistent, causing a lot of
convert the number to a string and then concatenate the two strings together:
"2" + 8;
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;
Another neat way of converting a string to an integer is to simply place a + symbol in front
Search WWH ::