Data Type Conversion In JavaScript
In this lesson you will learn about the wonderful world of type conversion in JavaScript!
Before proceeding, it's a good idea to ensure that you have a solid understanding of data types and operators.
We will cover:
What is type conversion?
Often in programming we need to perform some kind of type conversion, and in this lesson you will learn how to convert one data type to another in JavaScript.
There are two categories of type conversions:
- Implicit conversion
- Explicit conversion
In implicit conversion, JavaScript converts the type automatically. This is also known as type coercion whereby types are implicitly coerced from one to another.
Conversely, with explicit conversion we convert the type manually.
Let's explore some examples in order to illustrate each of these methods more concretely.
Implicit conversion
Implicit conversion works differently depending on the combinations of types and operators in use.
String conversion
If we attempt to add values with a numeric string type, JavaScript will convert the operand to a string and concatenate the values:
console.log(5 + '4'); // 54
Above JavaScript first converts 5
to a string so that the expression becomes:
'5' + '4'
Then these numeric strings are simply concatenated together to produce the string 54
.
A similar result occurs if we try to add a Boolean to a string:
console.log(false + '4'); // false4
false
is converted to a string and both operands are concatenated, so the output will be the string false4
.
While this behaviour may seem strange, it makes sense when you remember that the +
operator is reserved for concatenation when dealing with strings.
Number conversion
In contrast, if we attempt to use any of the other arithmetic operators on a numeric string value, such as subtract -
, multiply *
, or divide /
, the string is converted to a number.
Let's see what happens when we try to subtract one numeric string value from another:
console.log('10' - '3'); // 7
In this case, the strings '10'
and '3'
are first converted to numbers to become:
10 - 3
The calculation is then executed with the number values, resulting in the numeric result 7
.
If we use multiplication or division, the numeric strings will again be converted to numbers before the calculation is carried out:
console.log('4' * '6'); // 24
console.log('15' / '3'); // 5
NaN
If we try to perform calculations on non-numeric strings, the result will be NaN
. NaN
is a special property in JavaScript that represents a result that is 'not a number'.
While this may sound strange, these types of calculations can occur by mistake when data is passed through a program, and NaN
is usually a sign that either the incoming data is invalid, or there is a bug in the code itself.
Let's look at an example:
console.log('Frodo' - 'Baggins'); // NaN
Subtracting one non-numeric string from another will produce NaN
.
Boolean conversion
If we attempt to use Boolean values in combination with numeric strings, true
will be considered 1
and false
will be considered 0
.
We can demonstrate this by trying to subtract true
from the numeric string '10'
, which will result in 9
:
console.log('10' - true); // 9
Whereas subtracting false
is equivalent to subtracting 0
:
console.log('10' - false); // 10
It's worth mentioning that the data type null
is also treated as 0
:
console.log('10' - null); // 10
Undefined conversion
If we try to carry out any arithmetic calculations using undefined
the result will be NaN
:
console.log(10 + undefined); // NaN
This is the case whether undefined
is used in combination with a number, a Boolean, or a null
type.
Explicit conversion
As mentioned, explicit type conversion involves the manual manipulation of data types.
JavaScript provides us with a number of built-in methods that we can utilise to carry out these kinds of conversions.
Number
The global Number()
method enables us to convert strings or Boolean values to numbers.
In the real world, web forms accept strings as inputs that often need to be converted to the desired data type. For example, a user might enter their age as a string, that then needs to be converted to a number to perform calculations.
We can convert a numeric string to a number like so:
console.log(Number('10')); // 10
In this case the integer 10
will be output to the console.
If we instead pass the Boolean value true
, the result will be 1
:
console.log(Number(true)); // 1
Similarly, false
will convert to 0
. This matches the behaviour we saw for the implicit conversion of Boolean types.
An empty string will also be converted to 0
:
console.log(Number('')); // 0
In JavaScript, values are considered either 'truthy' or 'falsy'. Empty strings are defined as falsy because they represent the absence of a value. Truthy and falsy values are discussed in more detail later in this lesson.
parseInt
We can also use the parseInt()
method to convert a numeric string to an integer:
console.log(parseInt('8')); // 8
The above code will produce the number 8
.
It's worth noting that the Number()
and parseInt()
methods do behave differently, and choosing one or the other depends on the use case.
parseFloat
parseFloat
is similar to parseInt
, however it allows us to parse floating-point numbers from numeric strings:
console.log(parseInt('8.2')); // 8.2
This will return the floating-point number 8.2
.
String
The String
global method enables us to convert other data types to strings.
For example, we could convert a number like so:
console.log(String(43)); // 43
Here the string '43'
is logged to the console.
We could also convert a Boolean value:
console.log(String(true)); // true
The result will be the string 'true'
. The same can be achieved for other values like undefined
and null
:
console.log(String(undefined)); // undefined
console.log(String(null)); // null
toString
We can also use the toString()
method to convert data types to strings.
Here's an example with a number:
console.log((65).toString()); // 65
This will produce the literal string '65'
. Note that we need to wrap the number in parentheses ()
in order to invoke the method.
The String()
and toString()
methods differ slightly so, again, it depends on the use case. toString()
cannot be called on undefined
or null
, for example.
Boolean
The Boolean()
global method enables conversion of other data types to a Boolean type:
console.log(Boolean(4)); // true
In the above example the number 4
is truthy so it converts to true
.
Truthy and falsy
In this lesson we have encountered the idea of truthy and falsy values. This is a concept in JavaScript where all values will convert to a Boolean state.
The idea of 'truthy' and 'falsy' can seem confusing at first, however all values in JavaScript are considered truthy except for the following:
false
0
(numeric zero)-0
(numeric negative zero)0n
(BigInt of0
)''
(empty string)null
undefined
NaN
All of the above values are defined as falsy.
One example that often catches people out is a string containing only whitespace e.g. ' '
- this is considered truthy in JavaScript. Try it yourself by comparing Boolean('')
and Boolean(' ')
.
Being aware of these falsy values will help when dealing with dynamic types moving forward.
Summary
If you're feeling confused at this point, you're not alone. Many people find JavaScript type conversion challenging, including relatively seasoned developers. Indeed, it's one of the main reasons that TypeScript has become so popular!
Explicit type conversion is certainly more straightforward as it is, well, explicit! When performing explicit conversions you're literally declaring how the types will be transformed.
Implicit type conversion, on the other hand, isn't so obvious. While you're unlikely to write these calculations intentionally, it's good to be aware of how types are implicitly coerced in JavaScript in the event that you run into unexpected bugs in your code.
Please note that you're unlikely to remember all of these behaviours at this stage, and that's ok! Most working JavaScript developers still get caught out by at least some of them.
The main takeaway at this stage is to have a high-level awareness that JavaScript is performing this implicit coercion under the hood.
Remember to take your time, try out the examples and, above all, play with the code yourself to develop your understanding.