Type conversion and coercion in Javascript

Photo by Tech Daily on Unsplash

Type conversion and coercion in Javascript

Hey guys, welcome back In this post I am going to describe in the detail What type of conversion and coercion means in Javascript

Conversion?

It simply means manually converting the data.

coercion?

It's the opposite of Conversion where JavaScript automatically converts the data.

let's have a look at Conversion

For eg: When we get the data from users as input in Javascript they are usually string in nature no matter an integer or date until it's converted. let's, suppose we want to calculate the Date of Birth in this case. We have to manually convert it to Number Screen Shot 2022-10-30 at 1.41.38 pm.png Here data is converted only inside the Number(dob+18) but the original is a string because it's inside ' '. Remember, Converting does not mean we can convert anything to a Number by simply putting Number() if we try to convert an actual string it returns NAN which also means not a number. Screen Shot 2022-10-30 at 1.47.30 pm.png

lets, move to coercion

Screen Shot 2022-10-30 at 1.52.43 pm.png It's quite tricky over here because the + sign triggers the coercion and concatenates the value if they are strings but the - sign subtracts if they are numbers in nature and values are integers even though they are strings. Concatenates don't mean adding but it means connecting. This is all done by the Coercion feature of javascript automatically.