Type Conversion
So, In the previous article we learned that variables have different data types. However, there are some situations, where we get a different data type from the user than what we expect.
TypeOf Keyword
Section titled “TypeOf Keyword”Before starting this post, let me introduce you to typeof keyword. You might be wondering how do I know what type a variable is of? Right?
It’s easy we can use typeof keyword as shown in example.
let name = "Sam"
console.log(typeof name) // outputs string
The above example shows the data type of variable name being printed out on the console (terminal) and is of type String.
It’s that simple to know data type of any variable using this special keyword.
Remember the confusion section in last article? We cleared confusion about String, Boolean and Numbers.
Here’s an example:
let price = "10"
Hmm, we can see that the price is a String. However, we wanted a Number in our application but got String instead.
Now you might be wondering that “Hey I can take Number as Input from User. Problem Solved. No Big Deal!”. Well, that’s not how things work in real life.
See, when you build a website or an App, let’s say you want to get age from User, you might think that you will get Number, but in reality, apps and website returns all data as String in most of the cases.
So, what do we do when we expect a Number, but get a String? Or when we get different data types than what we expect?
This is the Scenario, where Type Conversion comes into play!
Definition
Section titled “Definition”Type Conversion is a process of converting a variable’s data type from one type to another.
Let’s understand this concept more in-depth with an analogy.
Suppose you are traveling from United States to Europe. Now you have dollars (USD) but to buy anything in Europe, you need the euros (EUR).
So, you went to a Currency Exchange Booth and converted your money from USD to EUR. This is Exactly what Type Conversion is all about.
Types of Type Conversion
Section titled “Types of Type Conversion”Now, that we know what Type Conversion is and what it does! Now it’s time to go beyond and learn it’s types. Type Conversion happens in two different ways in JavaScript:
- Implicit Type Conversion (Coercion)
- Explicit Type Conversion (Type Casting)
Implicit Type Conversion
Section titled “Implicit Type Conversion”Implicit Type Conversion is also known as Type Coercion. In this method, the JavaScript itself converts the data type of a variable.
Currency Exchange Analogy
Section titled “Currency Exchange Analogy”Let’s take the above Currency Exchange example again. Now as we need to convert from USD to Euro. Let’s say you have an international credit card for payments. In this case your bank automatically converts the currency behind the scenes without you worrying about anything.
Similarly, JavaScript converts data types behind the scenes to make things a little easier (or sometimes a little confusing).
let data1 = 2
let data2 = "2"
let sum = data1 + data2
console.log(sum) // outputs 22
In above example, we take two variables data1 and data2 which are Number and String Respectively. Then we create a third variable sum and add values of both variables. What do you think would be the output?
you might think like this.
x = 2
y = 2
z = x + y
z = 2 + 2
z = 4
You might think that output would be 4, just like we did Maths in Schools right? Well to your surprise, the answer is 22.
Shocked? Reminded of the popular meme ? 2 + 2 = 22 ?
Well let’s see what’s happening here in detail. Here’s a little modified code example from top. Now we have added multiple typeof keywords to see what’s happening.
let data1 = 2
let data2 = "2"
let sum = data1 + data2
console.log(typeof data1) // outputs number
console.log(typeof data2) // outputs string
console.log(typeof sum) // outputs string IMPORTANT
console.log(sum) // outputs 22
In above example:
- data type of
data1-> Number - data type of
data2-> String - data type of
sum-> String
Hmm, if you observe here. What is String. It’s just text right? Collection of words. Programming language sees it as words combining of alphabets.
How to write word Happy? -> H + a + p + p + y
So, if we see here, did JavaScript just converted data1 which is a Number to String? Well Yes!
why 22 instead of 4?
Section titled “why 22 instead of 4?”When using +, if either side is a string, JavaScript converts the other to a string too → "2" + "2" → "22". That’s why the result is "22", not 4.
This is Implicit Type Conversion on play! JavaScript secretly behind the scenes converted the number to a text essentially and then simply joins it. If you see the end result sum is a String as well.
Sometimes JavaScript’s automatic conversions help. But as you’ve seen, they can also surprise you!
That’s why we often do conversions explicitly — to stay in control. Let’s see how.
Explicit Type Conversion
Section titled “Explicit Type Conversion”Explicit Type Conversion is also known as Type Casting. In this case, we (the developers) tell JavaScript exactly how we want to change the data type.
Currency Exchange Analogy (cont…)
Section titled “Currency Exchange Analogy (cont…)”Let’s take the above Currency Exchange example again. Now you don’t have an international credit card but have dollars as cash. So now you need to find an Exchange Booth and manually convert you currency and then you can purchase something from the country. Here it’s done manually by you rather than your bank.
That’s exactly what explicit type conversion is! You choose when to convert a value, and to what type.
let price = "10"
let convertedPrice = Number(price)
console.log(typeof price) // outputs string
console.log(typeof convertedPrice) // outputs number
console.log(convertedPrice + 5) // outputs 15
In above example, we got price as String from the user but that’s not what we want. We need Number in order to perform some calculations. Hence we can Explicitly convert it from String to Number by using Number() method.
Number() method will take any data type and will try to convert it to a number.
In above example:
- We received price as a
String“10” from the user, but we wanted a Number for calculations. - We created a
convertedPricevariable and usedNumber(price)method to convert it. typeof priceis still “string” -> we didn’t change the original variable.typeof convertedPriceis “number”.- We can now add 5 to
convertedPriceand get a proper mathematical result: 15.
Without Conversion?
Section titled “Without Conversion?”If we didn’t explicitly convert 10 from String to Number, can you guess what the output would be? Well in that case, the output would be 105 since, JavaScript would do Implicit Conversion and we would get wrong result.
Primitive Type Conversion CheatSheet
Section titled “Primitive Type Conversion CheatSheet”| From | To Number | To String | To Boolean |
|---|---|---|---|
"33" |
33 |
(already string) | true |
"33abc" |
NaN |
(already string) | true |
"" (empty string) |
0 |
(already string) | false |
"0" |
0 |
(already string) | true |
true |
1 |
"true" |
(already boolean) |
false |
0 |
"false" |
(already boolean) |
null |
0 |
"null" |
false |
undefined |
NaN |
"undefined" |
false |
{} (object) |
NaN |
"[object Object]" |
true |
0 |
(already number) | "0" |
false |
1 |
(already number) | "1" |
true |
NaN |
(already number) | "NaN" |
false |
🧵 Wrapping It Up
Section titled “🧵 Wrapping It Up”So, now you have learned one of the most important topics in JavaScript about Type Conversions. Understanding this section properly is a great way to avoid 1000s of bugs in large codebases. It’s because of these reasons that TypeScript is becoming popular in recent years.
With good knowledge of type conversions, you can write a really solid code!