DEV Community

Zouhair Sahtout
Zouhair Sahtout

Posted on

Type Conversion and Type Coercion - JavaScript

Type Conversion:

In programming, type conversion or type casting is the process of explicitly converting a value from one type to another.
For instance, you may have a string value of '5' and you want to convert it to a number value of 5 so that you can do some arithmetic operations on it.

Converting a string into a number using Number() or the unary plus (+) operator.
Image description

Trying to convert the string 'Zouhair' into a number results in NaN (Not-a-Number).
Image description

NaN is a special value in JavaScript, representing an "Invalid Number."
Image description

We actually get a special "number" called NaN, which stands for Not a Number... Yeah, that's JavaScript for you. A number that is "not a number". There are some really strange and quirky aspects of JavaScript. The good news is that most of it doesn't get in your way in practical development. It's just when we start to dig down deeper.

Type Coercion

Type Coercion is when data types are converted implicitly by JavaScript.
Although the conversion that we did mention above can also be called explicit coercion. There's so many different words for the same thing in programming.
Typically coercion happens when you apply operators to values of different types.
Image description

The "+" operator trigger a coercion to strings so whenever an operation between a string and number, the number will convert to a string, and that's exactly what's happen in the template literals.

Image description
The "-" operator triggers coercion to numbers converting strings to numbers.

In summary: Type Conversion involves explicitly changing the data type of a value using functions like Number() and String().

On the other hand, Type Coercion is the automatic conversion that occurs during operations between values of different types, such as when the "+" operator converts numbers to strings and the "-" operator converts strings to numbers.

Top comments (3)

Collapse
 
abc_wendsss profile image
Wendy Wong

Hi Zouhair, Thank you for publishing your article on DEV and sharing with code snippets showing us how to apply type conversion and type casting. Welcome to the DEV Community! 😁

Collapse
 
zouhair_sahtout profile image
Zouhair Sahtout

Hey Wendy, Well thank you for your positive words that means a lot.

Collapse
 
abc_wendsss profile image
Wendy Wong

You're very welcome Zouhair :)