Type Conversion and Type Coercion in JavaScript : An Introduction

Type Conversion: We manually convert one data type to another.

Type Coercion: JavaScript automatically converts data types behind the scenes for us.

Type Conversion

Type Conversion is said to happen when the programmer explicitly transfers data from one data type to another.

Even though JavaScript implicitly transfers data from one data type to another for us in most cases, at times we will need to manually do this. Consider the below case:

const messiGoals = “672”;
const messiAssists = “266”;

const messiTotalGoalContributions = messiGoals + messiAssists;
console.log(messiTotalGoalContributions);

// Output will be 672266 and not 938 !!

Why? Because both messiGoals and messiAssists are variables of string data type and using ‘+’ between them will result in string concatenation and not addition.

So how do we get around this? Type Conversion is the answer. Let’s rewrite the code to include type conversion:

const messiGoals = “672”;
const messiAssists = “266”;

const messiTotalGoalContributions = Number(messiGoals) + Number(messiAssists);
console.log(messiTotalGoalContributions);

// Output will be 938 now. 
// The data type of both messiGoals and messiAssists still remains string.

So the above example demonstrates how to take two string values and convert them to numbers using type conversion to carry out mathematical operations using them.

Let’s take another example:

console.log(Number(‘Abdul Kalam’));
// Output will be NaN

What is NaN?

NaN means “Not a Number”. It actually refers to an invalid number. We get NaN whenever a mathematical operation fails to give us a new number.

Type Coercion

Type Coercion in JavaScript happens whenever an operator is dealing with two values that have different data types. In this case, JavaScript will implicitly convert one of the values to match the data type of the other value.

Let’s look at a simple example:

console.log(“Messi was at FC Barcelona for the past “ + 21 + “years!”);

In the above example, 21 will get type casted to string to match the data type of the first string.

Let’s look at more examples:

console.log(‘10’ - ‘5’ - 3);
// Output: 2
// When we use the ‘-’ symbol along with a mix of strings and numbers, 
// all values get converted to Number.
console.log(‘10’ + ‘5’ + ‘3’);
// Output: 18
// When we use the ‘+’ symbol along with a mix of strings and numbers, 
// all values get converted to String.
console.log(‘10’ * ’5’);
// Output: 50
// String got converted to Number
console.log(‘10’ / ‘5’);
// Output: 2
// String got converted to Number
console.log(‘10’ > ‘5’);
// Output: true
// Even for comparison operators, strings get converted to Number

So the only case in which Number gets converted to String is when we use the ‘+’ operator amongst a mix of strings and numbers.

If you want to learn more about type coercion, consider reading this this article by Alexey Samoshkin.

Thanks for reading :)