Type Conversion and Coercion

Introduction to Type Conversion and Coercion.

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.

Get hands-on with 1200+ tech skills courses.