Type coercion means that when the operands of an operator are different types, one of them will be converted to an “equivalent” value of the other operand’s type. For instance, if you do:

boolean == integer

the boolean operand will be converted to an integer: false becomes 0true becomes 1. Then the two values are compared.

However, if you use the non-converting comparison operator ===, no such conversion occurs. When the operands are of different types, this operator returns false, and only compares the values when they’re of the same type.

Type coercion is the process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion. To recall, primitives are: number, string, boolean, null, undefined + Symbol (added in ES6).

Implicit vs. explicit coercion Type coercion can be explicit and implicit.

When a developer expresses the intention to convert between types by writing the appropriate code, like Number(value), it’s called explicit type coercion (or type casting).

Since JavaScript is a weakly-typed language, values can also be converted between different types automatically, and it is called implicit type coercion. It usually happens when you apply operators to values of different types, like 1 == null2/’5'null + new Date(), or it can be triggered by the surrounding context, like with if (value) {…}, where value is coerced to boolean.

One operator that does not trigger implicit type coercion is ===, which is called the strict equality operator. The loose equality operator == on the other hand does both comparison and type coercion if needed.

Implicit type coercion is a double edge sword: it’s a great source of frustration and defects, but also a useful mechanism that allows us to write less code without losing the readability.

Three types of conversion The first rule to know is there are only three types of conversion in JavaScript:

  • to string
  • to boolean
  • to number

Secondly, conversion logic for primitives and objects works differently, but both primitives and objects can only be converted in those three ways.

Let’s start with primitives first.

#web-development #javascript-coercion #type-coercion #coercion #javascript

Type Coercion in JavaScript
1.20 GEEK