Type Conversion and Coercion
Introduction to Type Conversion and Coercion.
We'll cover the following...
Introduction
Often, we need to change value types in programs. For instance, a string may need its number updated after an arithmetic operation. For that, we change that number from string to a number type, do the arithmetic, and then change it back to a string.
For this, in JavaScript, we have type conversion. Type conversion is changing a value from one type to another.
Since JavaScript is a weakly-typed language, at-time type conversions are done automatically. This leads to two types of type conversion:
- Implicit type conversion
- Explicit type conversion
Implicit Type conversion / Type coercion
The type conversion that happens automatically is the implicit type conversion, also known as type coercion. This usually happens when we apply operators to two different types of values. Look at the example below.
console.log(1 + '1' , typeof(1 + '1')); // prints a string valueconsole.log(null == 'null', typeof(null == 'null')); // prints a boolean value
In the above code, JavaScript automatically converts types of the two operands so that the two operands are of the same type. This allows the operator to process the operands and eventually give ...