Type Casting in JavaScript
Tags: webdev, javascript, beginners, programming
Published: 2023-05-13 19:35:18

Typecasting in JavaScript is the conversion of one data type into another data type, for example, a number to a string. Typecasting is often also known as type conversion.

## What is data type?
JavaScript has 8 main data types:

- String
- Number
- Boolean
- Null
- Undefined
- Bigint
- Symbol
- Object

The object can be divided into more data types or to be more precise there are data types that are also objects:

- Array
- Object
- Date

JavaScript is a dynamic language with dynamic data types because variable types are defined the moment they are assigned the value. Check out my post to learn more about [data types](https://dev.to/catherineisonline/javascript-data-types-5ec5) if you don't have prior knowledge.
There are two types of typecasting - implicit typecasting and explicit typecasting.

##The implicit typecasting
The implicit type conversion takes place automatically by the [interpreter](https://en.wikipedia.org/wiki/Interpreter_(computing)) or the [compiler](https://en.wikipedia.org/wiki/Compiler) when there is an internal requirement for that.
To understand what I mean exactly, let's go through several examples.

### The implicit typecasting of strings with plus to strings
When you try to add any data type to a string, JavaScript will convert anything to a string. A string plus anything else even if not a string, will be converted to a string automatically. Note that this works like this only with a plus because any other math operation will return a NaN(Not a Number).


![The implicit typecasting of strings with plus to strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syeqylz1rhliyw7kacum.png)



### The implicit typecasting of numeric strings to numbers
When you have a numeric value in a string but you perform a math operation (specifically subtraction, multiplication, or division) with another numeric value, the numeric string will be converted to a number. Note that this does not work with a plus.


![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ootamadeoc7hn95y3dmz.png)



Also, both values can be a string with a numeric value as well and as a result, you will still receive a number.


![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyo0kolhelt7mtk5dh19.png)



If there are any other types with such math operations rather than a number or a numeric string, there are some other behaviors that we will go through shortly.

### The implicit typecasting of booleans to numbers
If you use booleans in math operations with numbers then true is always converted to 1 and false is always converted to 0. Note that if it's a numeric string (a number in the string) then plus will convert the boolean to a string but anything else will convert the numeric string into a number.

#### Number + boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z58hndljnysnbod3sqyz.png)



#### Numeric string + boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3yg4xpa3pllsn9rfthb1.png)



#### A number - boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phakv1doh9bu4hlssk0n.png)



#### Numeric string - boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5wabdkmjzlgrap8lw0b.png)



#### Number/boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7yas5jzbdbb0yotcqdr.png)



#### Numeric string/boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96n40lc763jvzxzieo46.png)



#### Number * boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1fulxqmdgk8cdv79ogaq.png)



#### Numeric string * boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wg7zu2hbrq8ctrdv3tz8.png)



### The implicit typecasting of null to numbers
When used with numbers, null is converted to 0 whether it's a plus, minus, division, or multiplication.


![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwvt7bk3xoz29hcekkzo.png)



### The implicit typecasting of undefined
Performing operations with undefined always returns NaN whether it's a boolean, number, or null. Although an undefined plus string will convert it to a string as we learned earlier.

#### Undefined with numbers

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13078qtnet95l8j7lz0d.png)



#### Undefined with null

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrk6gbygyk5fxunxacpn.png)



#### Undefined with boolean

![The implicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gltbsa322s5of7vbu5q7.png)



## The explicit typecasting
Opposite to implicit typecasting, explicit typecasting means data type conversion manually. This can be achieved via various built-in methods. Built-in methods are functions that already exist in JavaScript and you don't create them yourself.

### The explicit typecasting to number
To convert anything to a number you can use the method Number(). However, the result will be various depending on the data type.

#### String to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enj7zotmk9xedgzzdkmr.png)



#### Numeric string to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j96az681bfoseklvsysg.png)



#### Boolean (true) to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5m1pmy8wojwxa915u8t.png)



#### Boolean (false) to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssjtjjrmwojwsckczv6c.png)



#### Null to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swen03kcn09yoenqyxnp.png)



#### Undefined to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fvwbonmsp7rs697y9rj.png)



#### Empty string to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihhevd3felqi7ohr6bnj.png)



#### Date to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hgw9ltv7tdo36djs2i9a.png)



Note that the date itself is an object, not a number and the output will be different for you because the new Date() returns milliseconds elapsed since the start of 1970 in UTC, which hopefully has changed ever since I wrote this code.

### The explicit typecasting to string
To convert anything to a string you can use a String() method or toString(). Mostly we use toString() but it might give a different result in some situations.

#### Number to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8x31gl00dtrozsxzef1.png)



#### Null to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o02j6t96elhi5x0qovzp.png)



#### Undefined to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqai857z9521hzfum87r.png)



#### NaN to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6am4qbnwwtj7dl7zb8y2.png)



#### Boolean (true) to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gl4gdke2t0udb4j44te8.png)



#### Boolean (false) to a string

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zgbn4pk6708yvof8op5.png)



#### Date to a number

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clmsx5o8zu7oat6j0cir.png)



### The explicit typecasting to boolean
To convert a data type to a boolean we can use the method Boolean(). This conversion can be divided into two parts to make it easier to remember. First, we will group those that return true and then we will group those that return true, simple as that.

### The explicit typecasting to false
The data types that confer to false using the Boolean() method are undefined, null, 0, NaN, '' (an empty string without space).

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxn7d3cnrsaul1mgye3t.png)



### The explicit typecasting to true
Strings, numbers, and strings that have space convert o true if we use the method Boolean().

![The explicit typecasting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hw5m2jqz16mh6a2bu8c.png)



## Converting arrays to objects
There are several ways to convert arrays to objects. Let's go through each of them.

### The spread operator
A spread operator is an easy way to spread an array inside the object.

![Converting arrays to objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mj966fahx1j2l2d9w7l.png)



### A for loop
Another way to create an object from an array is to loop through an array and create a key with the array item index and add an array item at a relevant position to the value.

![Converting arrays to objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itlkmklb5x4stdi80rl2.png)



### A forEach loop
A very similar way will be looping through an array via forEach loop.

![Converting arrays to objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5ywhouk05kihosfoa50.png)



### With the Object.assign()
Next, you can use an object built-in method Object.assign() to merge an array with an object

![Converting arrays to objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4nbpp2y1a6armwpcpe41.png)



### With the Object.fromEntries()
Finally, you can use another object method Object.fromEntries(). However it will only work if you have a 2-dimensional array, otherwise, it will throw an error.

![Converting arrays to objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mq4prnj7zp7g4k1xe4rl.png)



## Converting objects to arrays
To convert objects to arrays there are several built-in methods that we can use. Let's check them out.

### With the Object.entries()
We used a similar method to convert arrays to objects and we can do the same by using entries. It will return a 2-d array with 3 arrays from each key-value pair.

![Converting objects to arrays](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npza55wi5v4idldsnbhc.png)



### With the Object.keys()
Next, we can use a keys method that retrieves only the keys of the objects.

![Converting objects to arrays](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eu75t89k50j79aajs2m8.png)



### With the Object.values()
Finally, we can do the same but with the values of the object this time

![Converting objects to arrays](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z48zxq6ukprdcmyw77o3.png)



## Type conversion vs Type coercion
Both type conversion and type coercion do sound and seem similar however they are different things. When we say type coercion it always is an implicit typecasting. If you remember, implicit means that it's done automatically so to remember it easier consider coercion and implicit kind of synonyms because coercing means 'persuading someone to do something by threading or force'. So it does kind of associate with the implicit because it's done automatically, 'by force'.
Type conversion however refers to the general process of typecasting whether it's an implicit or explicit one.

## Summary
Typecasting in JavaScript refers to the conversion of one data type to another data type, such as a number to a string. JavaScript has eight primary data types, including string, number, boolean, null, undefined, bigint, symbol, and object. The object type can be further divided into additional data types, such as array, object, and date. JavaScript is a dynamic language with dynamic data types because variable types are defined when they are assigned a value. Typecasting in JavaScript can be done explicitly or implicitly. Implicit typecasting is automatic when the interpreter or compiler requires it. Explicit typecasting is performed manually using built-in methods. The Number() method is used to convert anything to a number, and the String() or toString() method is used to convert anything to a string. The Boolean() method is used to convert a data type to a boolean. In addition, arrays can be converted to objects using the spread operator or a for loop.