Type Coercion & Conversion

Open the project folder

In our starter files, open the index.html page from this lessons folder:

06.Loops-and-conditionals > 08.Type-coercion-conversion

Type coercion

Coming up, we will cover some type and true or false related things, which can give you some strange or unexpected results. Being aware of these can help you understand things like why an if statement is not running correctly and save you a lot of time debugging.

The first one is type coercion. We know about types such as objects, strings and Booleans. And type coercion relates to how the values of data types are converted to other data types.

Looking at this lessons folder, we have an example:

const number1 = '7';
const number2 = 2;
const total = number1 + number2;
console.log(total);

We have two variables which we add together. Both variables are numbers, but the first is surrounded in quotes making it a string.

Looking at the total variable, we add together the variables using the + operator. This is important here since this can be used to either join two strings or add two numbers.

Since our variables are a number and a string, what will happen? Rather than cause an error, JavaScript is designed to choose one data type to convert to automatically, and this is called coercion.

It can choose to convert so they are both strings or both numbers. In the console you will see a string value of 72, rather than number value of 9. This conversion has happened automatically for us, and this can be referred to as implicitly. This implicit conversion is what coercion is.

Type conversion

Something similar is type conversion. This works like coercion by converting a value from one data type to another, but we can also do this ourselves manually. If we wanted this to be converted to a number manually, we have a Number() method available:

const number1 = '7';
const number2 = 2;
const total = Number(number1) + number2;
console.log(total);

Now the console value is 9. We must be careful with this when using it with things like if statements. Here we may be using an if statement to check if a certain number is present, but the string conversion could give us unexpected results.

To recap, coercion happens implicitly or automatically, type conversion can also happen manually too. Sometimes these words are used interchangeably, but this is the difference.

We could also do the opposite and use String() method to wrap our number:

const total = number1 + String(number2);

This means we now join two string values resulting in 72. It may be good to always convert incoming data to what we want it to be. If for example we are getting data from a third party, we can eliminate bugs and errors by making sure our data type is correct.

For this reason, you may have heard of tools such as Typescript, which enforces us to declare the type of data we are using up front. This can eliminate errors in our code.

Potential unexpected results

This is how things work with the addition operator, but other operators can also give unexpected results after coercion has applied. We can also see this coercion in action with the greater than or less than operator:

const number1 = '7';
const number2 = 2;
console.log(number1 > number2);

We are still comparing a string and a number, but JavaScript is comparing them as though they were both numbers. This example will result in true as 7 is greater than 2. This is strange behaviour for people used to other programming languages which are strongly typed, meaning data is constrained to a certain type.

Although this coercion happens behind the scenes, these examples so far have sensible and predictable behaviour.

However, this is not always the case. Take incrementing for example:

// 1. change to let
let number1 = '7';
// 2. increment by 1
number1++;
const number2 = 2;
const total = number1 + String(number2);
// 3. log:
console.log(number1);

The result is 8. The string of 7 is converted to a number, we should not be able to increment a string by 1.

What about if this was a single array value:

let number1 = "7";
number1++;
console.log(number1);

Again, the result is 8 and this makes no sense, but this is the world of JavaScript. Let’s try adding a number to an array:

let number1 = ["7"] + 2;
console.log(number1);

Again, a crazy example, and this one is 72 this time. These numbers have been joined together as a st

Testing the data type

We can prove this is a string using the typeof operator:

let number1 = ["7"] + 2;
console.log(typeof number1); // string

And here is something else strange too. This is a string as we can see in the console, what do you think will happen if we re-introduce the increment?:

let number1 = ['7'] + 2;
number1++;
console.log(typeof number1); // number

The resulting type is number. We are adding together “7” from an array with 2, giving us a string of 72. Then as we looked at before, incrementing a string will convert it to a number, giving us a value of 73.

The equality operator

And the equality operator introduces a whole new world of things to watch out for too.

console.log(1 == true); // true

What about another number:

console.log(0 == true); // false

To recap, 1 was equal to true, and 0 was equal to false.

When using the double equals, this is a loose equality. Meaning it is not checking types, unlike the triple equals (===).

Since we are comparing a number with a Boolean, we don’t have two equal types to check. JavaScript will therefore convert using coercion. In this case, it converts the Boolean to a number where 1 represents true, and 0 represents false. All numbers other than 1 weill result in false.

So, that’s a lot of quirkiness, and it doesn’t end there either, JavaScript has so many of these things we have to watch out for, but knowing this behaviour exists can give you a head start knowing where to look if you are encountering bugs or unexpected behaviour in your code.