JavaScript WordBook

Providing simple explanations for seemingly complex development terms

Type coercion

Type coercion is the conversion of a value from one type to another. This is common in many languages including Java, C and JavaScript.


A simple example of type coercion is changing a number to a string.

If and when type coercion occurs varies depending on the code being run. It can even happen automatically, so you may have come across it, even without realising.

For example when running a loose equality comparison (==):

// Javascript
if (5 == '5') {
  console.log('true');
}

As this a loose comparison (==), type coercion occurs and the test will pass. This is because when performing a loose comparison, type coercion occurs on one of the operands, converting it to an equivalent value of the other operand type. For example, converting the number 5 to a string would result in a match.

If this was a strict comparison (===), type coercion would not occur and the operands would not match as their types are not equivalent, which would result in a failed comparison.

A loose comparison can also be referred to as an abstract or double equals comparison and a strict comparison can also be referred to as identity or triple equals comparison.

Implicit vs explicit

When type coercion happens automatically, like in the above example, this is called an implicit type coercion.

Type coercion can also be explicit, which is known as type casting. This is when a function is used to convert the type, such as the String(), Boolean() or Number() functions in JavaScript. These functions take an argument and return the requested type. For example:

// Javascript
String(12) // returns the string 12 

Understanding type coercion can be a vital part of understanding how a program will run. Check out the further content links below for more information on type coercion.

Synonyms

  • Type conversion
  • Type casting
  • Type juggling

Recommended reading