In JavaScript coercion (sometimes called cast) is the process of converting a data type value into another.
JavaScript is a dynamically typed language. That is, it does most of the type management work for us. But that does not mean it has no types (it does, just like all other programming languages).
Furthermore, JavaScript has been designed from the beginning to simplify type management. This includes the simplification of type conversion.
In fact, one of its features is that it sometimes tries to convert “extra” units, being very “creative,” leading to unintuitive situations for which it is criticized (¿unjustly?).
In any case, converting between data types is necessary on many occasions (and even more so understanding them, because as I said, sometimes JavaScript is overly creative).
There are two types of coercion in JavaScript: explicit coercion and implicit coercion.
- Explicit coercion occurs when one converts a data type into another using a function or an expression.
- Implicit coercion occurs when JavaScript automatically converts a data type (without being explicitly instructed to do so).
Implicit Conversion
Implicit conversion occurs when JavaScript automatically converts a value to another data type based on the context in which it is used.
This process is “triggered” automatically when performing an operation (such as using an operator or using a structure like a loop or conditional).
Converter by Operator
Arithmetic Operation
JavaScript converts strings to numbers when performing arithmetic operations.
let resultado = '5' - 2; // '5' is converted to the number 5
console.log(resultado); // Prints: 3
In this case, the string '5'
is converted to the number 5
before performing the subtraction.
Concatenation Operation
In string concatenation and other types, JavaScript converts values to strings.
let saludo = 'El número es ' + 7; // 7 is converted to the string '7'
console.log(saludo); // Prints: El número es 7
Here, the number 7
is converted to the string '7'
to concatenate it with 'El número es '
.
This leads to many unintuitive errors because +
is both an arithmetic operator and a comparison operator.
Comparison Operation
Equality comparisons (==
) can also involve implicit coercion.
console.log(5 == '5'); // Prints: true
In this example, JavaScript converts the string '5'
to the number 5
to compare the two values.
Logical Operators
Logical operators (&&
, ||
) can perform implicit coercion to convert values to booleans.
console.log('' || 'Hola'); // Prints: Hola
Here, the empty string ''
is converted to false
, and the ||
operator returns 'Hola'
.
Conversion by Function
Boolean conversion is commonly used in control structures like if
, while
, and logical operators. Values that convert to false
are known as falsy values, while all others are truthy.
if ('texto') {
console.log('Siempre verdadero'); // Executes
}
if (0) {
console.log('Nunca verdadero'); // Does not execute
}
Eh… don’t do that, it’s a terrible practice. That’s what boolean values are for.
Explicit Conversion
Explicit conversion is the process in which we convert a value to a specific data type using built-in functions and methods in JavaScript.
Conversion to Number
Use Number()
to convert a string to a number.
let numero = Number('123'); // Explicit conversion to number
console.log(numero); // Prints: 123
You can also use parseInt()
or parseFloat()
to convert strings to integers or floating-point numbers, respectively.
let entero = parseInt('123', 10); // Convert to integer
let flotante = parseFloat('123.45'); // Convert to float
Conversion to String
Use String()
to convert a number or any other value to a string.
let cadena = String(123); // Explicit conversion to string
console.log(cadena); // Prints: '123'
The method .toString()
can also be used to convert numbers and other types to strings.
let numero = 123;
let cadena = numero.toString(); // Explicit conversion to string
console.log(cadena); // Prints: '123'
Conversion to Boolean
Use Boolean()
to convert a value to a boolean.
let esVerdadero = Boolean(1); // Conversion to boolean
console.log(esVerdadero); // Prints: true
Values that convert to false
in JavaScript include 0
, NaN
, null
, undefined
, and the empty string ''
.
Coercion of Primitive Types
In JavaScript, primitive types include string
, number
, boolean
, null
, undefined
, and symbol
. Each of these types has specific rules for coercion.
Data Type | Conversion to Number | Conversion to String | Conversion to Boolean |
---|---|---|---|
String ("123" ) | 123 | = | true if not empty |
String ("abc" ) | NaN | = | true if not empty |
Number (123 ) | = | "123" | true if different from 0 |
Number (0 ) | = | "0" | false |
Boolean (true ) | 1 | "true" | = |
Boolean (false ) | 0 | "false" | = |
null | 0 | "null" | false |
undefined | NaN | "undefined" | false |
Conversion to Number
- Text strings containing numbers are converted to those numbers.
- While non-numeric strings result in
NaN
. true
converts to1
.false
andnull
to0
.undefined
toNaN
.
Conversion to String
- All types can be converted to a textual representation using their value (for example,
true
converts to"true"
, andnull
to"null"
).
Conversion to Boolean
- “Falsy” values (
0
,false
,null
,undefined
,NaN
or an empty string""
) convert tofalse
. - While everything else is
true
.
How to Avoid Coercion Errors Tips
Coercion can lead to subtle and difficult-to-debug errors. To avoid these errors, it is important to keep the following tips in mind:
Use strict comparison operators (===
and !==
) instead of non-strict comparison operators (==
and !=
) to avoid automatic type coercion.
Explicitly convert data types using functions like Number()
, String()
, and Boolean()
.
Make sure data types are as expected before performing an operation. You can use the typeof
function to check the data type of a variable.
const num = '10';
if (typeof num === 'number') {