const - JS | lectureJavaScript Fundamentals 1

Type Conversion and Coercion

JavaScript Fundamentals 1

Type conversion is when we manually convert from one type to another. On the other hand, coercion is when JavaScript automatically converts types behind the scenes for us, which is necessary in some situations. Coercion happens implicitly and completely hidden from us.

script.js
const inputAge = '24';

Consider the above code snippet where we have a variable inputAge. Let's suppose it comes from an input field ( Input field values usually come as strings ) with a value of 24. If we now want to do some calculations with this, it won't work. You can try the below code to see what I mean.

script.js
// Try to add to more years to the user's age
console.log(inputAge + 2) // Result ==> '242'

The result '242' happens because, if you remember, when we have a string and add something to the string, it will concatenate the strings. So we can't expect that it will actually add the number 2 to our inputAge variable because inputAge is a string.

To fix this, we need to convert the string value in inputAge to a number. To do that, we use the built-in Number function. We will learn exactly what a function is in the upcoming lectures. Here is how to do it :

script.js
console.log(Number(inputAge))

Doing Number(inputAge) will return the string as a number. There is one important thing to keep in mind when doing this; the original value is not actually converted. The inputAge variable itself is still a string. It still holds the value 24 as a string not as a number. You can try this and see it for yourself :

script.js
let inputAge = '24';
console.log(Number(inputAge), inputAge); // Result ==> 24 "24"
console.log(typeof Number(inputAge), typeof inputAge); // Result ==> number string
console.log(inputAge + 2); // Result ==> 242

Using the Number function will give us a converted version. So, if you want to perform the calculation inputAge + 2, you need to do it like this :

script.js
console.log(Number(inputAge) + 2) // Result ==> 26

Now the question is, what if we're trying to convert something to a number that is impossible to convert? Let's try this :

script.js
console.log(Number('Paris'))

What will happen here is that JavaScript will look at the string 'Paris', will try to convert it to a number, but it won't work, and in the console, we will get NaN. NaN stands for Not a Number.

We get NaN from JavaScript whenever an operation that involves numbers fails to produce a new number. Basically, NaN means invalid number. It's not really Not a Number. Let me prove this to you :

script.js
console.log(typeof NaN) // Result ==> number

This proves that NaN means an invalid number. It's still a number but an invalid one.

Up till now we are converting strings to numbers; but we can do the opposite. To do it the other way round, you can use the String function this way :

script.js
// You can check the type if you wish: console.log(typeof String(24))
console.log(String(24))

Remember always to start the string function with a capital S, just like the Number function with a capital N.

JavaScript can only convert to three types. That is, to Number, String and Boolean. We can't convert to Null or undefined because that doesn't make sense.

Till now, we've only converted to numbers and strings but not to booleans; because booleans behave in a special way that we are going to see in the lecture "Truthy and Falsy Values".

In practice, we rarely convert manually from one type to another because JavaScript does type coercion automatically for us in many situations.

Remember that type coercion occurs whenever an operator is dealing with two values that have different types. In such a case, JavaScript will then, behind the scenes, convert one of the values to match the other value so that in the end, the operation can be executed. Let's have an example

script.js
console.log('Jacob has ' + 3 + ' daughters!')

As you might have guessed, the result will be Jacob has 3 daughters; but what actually happens for us to have this result? As I previously said, coercion occurs when we have different types, and on the above code, we have different types: a string, a number, and another string. The plus operator that we have triggers a coercion to strings. Whenever there is an operation between a string and a number, the number is converted to a string.

Thanks to type coercion, it will be exactly the same thing as writing this :

script.js
console.log('Jacob has ' + '3' + ' daughters!')

It's exactly the same thing that happens with template literals. It takes all the number values and converts them to strings. If automatic type coercion didn't exist in JavaScript; like many other languages don't, then we would have to manually do this, and we would have to do something like this :

script.js
console.log('Jacob has ' + String(3) + ' daughters!')

Not all operators do type coercion to strings. Let's have an example :

script.js
console.log('24' - '3' - 5) // Result ==> 16

The first time I saw this, I was like; ok, what happened here ? Did JavaScript convert those strings to numbers? Of course, it did! This is because the minus operator triggers the opposite conversion. In this case, strings are converted to numbers and not the other way around.

If we now change the minus operator and instead use the plus, what do you think will happen? I think you've guessed it; the number 5 will be converted to a string, and all the three strings will be concatenated.

It's a very important distinction to keep in mind because this confuses many JavaScript beginners when they don't know about this.

The same goes with other mathematical operators like division, multiplication, exponentiation and, logical operators like greater than, less than etc.