Photo by Pankaj Patel on Unsplash
Type Conversion Vs Type Coercion in JavaScript
Implicit Type Conversion vs Explicit Type Conversion in JavaScript
Type Conversion can be Implicit (which is automatically done by javascript during the execution of code) and Explicit (which is manually done by the programmer).
Implicit Type Conversion is also known as Coercion, While Explicit Type Conversion is known as Type Casting/Conversion.
What is the Type Coercion?
const a = "Hello" + 5;
console.log(a); // output - Hello5
In the above example, The number 5 is converted into a string by js, and a concatenation operation on 2 strings is performed, which results in the output - "Hello5".
const a = "Hello" - 5;
console.log(a); //NaN
Here, JS tried to convert the string 'Hello' into a Number and it could not be done so it is returned as NaN ie. Not a Number.
Note: In the case of the + operation between string and number there is coercion of number to a string and in the case of -, *, / operators, there is coercion of string to Number.
What is Type Conversion?
When we manually/explicitly convert one datatype to another, It is known as type conversion.
let a = Number("97");
console.log(a); // 97
console.log(typeof a) //number
In the above example, we have converted a string to a number using the method Number. using typeof function, we can check the datatype of the variable.
const num = String(23);
console.log(num, typeof num); //23, string
In JavaScript, We can convert to String, Number, and Boolean. We cant convert anything to null or undefined.