coercion-y-conversion-de-variables-en-javascript

Coercion and Conversion of Variables in JavaScript

  • 6 min

In JavaScript, coercion (sometimes called casting) is the process of converting a value from one data type to another.

JavaScript is a dynamically typed language. That is, it does much of the type management work for us. But that does not mean it doesn’t have types (it does, just like all other programming languages).

Furthermore, JavaScript was conceived from the beginning to simplify type management. This includes simplifying type conversion.

In fact, one of its characteristics is that sometimes it tries to convert units “too much”, being very “creative”, and leading to unintuitive situations for which it is criticized (unfairly?).

In any case, converting between data types is necessary on many occasions (and even more so understanding them, because as I say, sometimes JavaScript is too creative).

There are two types of coercion in JavaScript: explicit coercion and implicit coercion.

  • Explicit coercion occurs when you convert one data type to 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 converts a value to another data type automatically 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 a conditional).

Conversion 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
Copied!

In this case, the string '5' is converted to the number 5 before performing the subtraction.

Concatenation Operation

In string concatenation with 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
Copied!

Here, the number 7 is converted to the string '7' to be able to concatenate it with 'El número es '.

This leads to many unintuitive errors, because + is both an arithmetic operator and a concatenation operator.

Comparison Operation

Equality comparisons (==) can also involve implicit coercion.

console.log(5 == '5'); // Prints: true
Copied!

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
Copied!

Here, the empty string '' is converted to false, and the || operator returns 'Hola'.

Conversion by Function

Conversion to boolean 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
}
Copied!

Eh… don’t do that, it’s a very bad practice. That’s what boolean values are for.

Explicit Conversion

Explicit conversion is the process where 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
Copied!

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
Copied!

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'
Copied!

The .toString() method 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'
Copied!

Conversion to Boolean

Use Boolean() to convert a value to a boolean.

let esVerdadero = Boolean(1); // Conversion to boolean
console.log(esVerdadero); // Prints: true
Copied!

Values that convert to false in JavaScript include 0, NaN, null, undefined, and the empty string ''.

Primitive Type Coercion

In JavaScript, primitive types include string, number, boolean, null, undefined, and symbol. Each of these types has specific rules for coercion.

Data TypeConversion
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"=
null0"null"false
undefinedNaN"undefined"false

Conversion to Number

  • Text strings containing numbers are converted to those numbers.
  • While non-numeric strings result in NaN.
  • true converts to 1.
  • false and null to 0.
  • undefined to NaN.

Conversion to String

  • All types can be converted to a textual representation using their value (e.g., true converts to "true", and null to "null").

Conversion to Boolean

  • “Falsy” values (0, false, null, undefined, NaN, or an empty string "") convert to false.
  • While everything else is true.

How to Avoid Coercion Errors tips

Coercion can lead to subtle and hard-to-debug errors. To avoid these errors, it’s 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.

Convert data types explicitly using functions like Number(), String(), and Boolean().

Ensure that 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') {
Copied!