JavaScript: What is Type Coercion and Type conversion?

JavaScript: What is Type Coercion and Type conversion?

JavaScript is a loosely typed programming language, meaning variables can store any values of any data type, and type coercion would take place when operations or comparisons involve values of different types.

Types Of Type Coercion

There are two types of JavaScript type coercion:

  1. Implicit Type Coercion

  2. Explicit Type Coercion

Implicit Type Coercion

As the name implies, implicit type coercion takes place unexpressed, that is it occurs automatically during operation or comparison where the operands are of different types without the programmer's instruction. What JavaScript does is, it converts one or both of the values to a common type before performing any operation on them.

Number to String Coercion

Implicit type coercion from number to string only when the addition(+) sign is used, because JavaScript sees it as a concatenation and so concatenates the number with other string at the output.

see the example below;

String to Number Coercion

When other operators are used except the addition operator, JavaScript implicitly converts any other data type (String, Boolean, and so on…) to a number data type. Also, know that in the case of boolean coercion, JavaScript sees True as (1) while False as (0) since it is a zero base language.

See example below;

Explicit Type Coercion

Explicit type coercion also known as “type conversion” is the process where the coercion is done by the programmer. The programmer intentionally converts a value from one data type to the other.

Number to String Conversion

It converts a number data type to a string data type explicitly, and it is done by the programmer.

See example below;

String to Number Conversion

It converts a string data type to a number data type explicitly with the programmer intentionally doing it.

see the example below;

Many other JavaScript types can be converted from one type to the other, which includes boolean and so on.

Conclusion

Implicit type conversion enables the developer more control over the conversation process and it should be used carefully to avoid unexpected errors.