Type Coercion & Type Conversion

Type Coercion & Type Conversion

This is one of the most important topic every Javascript DEV must know. The common thing in both of them is converting a value from one type to another. But the way they do is different.

Type Coercion

The conversion of value is done implicitly (Behind the Scene) by javascript when trying to manipulate with the value of another type or the same type but other operators. Example below

let Age = 14 + '23';
console.log(typeOf Age);
// Prints the string value
// 1423

In the above example we are trying to add the number value with the string and the result is a string that converts the number value into string value.

Different Operators convert differently

like if I use a Multiplication operator instead of addition then it converts the string into a number. As per my experience, addition is only the operator which leads to the conversion of numbers to strings. All other operators convert the strings to Numbers.

Example of the Different operator:

// Multiplication
let mul = 45 * '2';
console.log(mul);
// 90

let div = '30' / 2;
console.log(div);
// 15

In the above example, we are using two different operators and looked at how type coercion works with different operators.

Operator Precedence in Type Coercion

One thing to remember is that here operator precedence does work. When you have to be careful when manipulating data when using multiple operators.

An example of operator precedence is given below

let plot = 45 + (45 + '5');
console.log(plot);
// Result: '45455'

let size = 45 + 45 + '5';
console.log(size);
// Result: '95'

In the above example, the values in brackets get first manipulated so the number is been added to a string so it gets converted to a string and the number outside the brackets again gets added to a string. ๐Ÿ˜ฐ Confusing, don't worry watch my operator precedence article to get a clear view about it.

It's not mandatory that on the other side, there should be a value of different type but even if all the operands are of the same time the conversion depends on the operator.

An example is given below:

let bill = '45' * '2';
console.log(bill);
// Result: 90

Here in the above code, both sides of the operands are of String type, and the multiplication operator is used which converts both the strings into numbers and performs the operation.

Type Conversion

It refers to manually converting the value. There are some methods to do that some are listed below.

Number(value) : Converts any value into a number.

varuable.toString() : Converts any value into a string.

An example is given below:

let age = 20;
console.log(age.toString());
// Results: '20'

let year = '2023';
console.log(Number(year));
// Results: 2023
ย