Language: EN

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

Coercion and Conversion of Variables in JavaScript

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 much of the type management work for us. But that does not mean it has no types (it has, just like all other programming languages).

Moreover, JavaScript has been designed from the beginning to simplify type management. This includes simplifying type conversion.

In fact, one of its features is that at times it tries to convert the units “too much,” 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 too creative).

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

  • Explicit coercion occurs when you convert one data type into another using a function or an expression.
  • Implicit coercion occurs when JavaScript automatically converts a data type (without being explicitly told 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 a conditional).

Operator Conversion

Arithmetic Operation

JavaScript converts strings to numbers when performing arithmetic operations.

let result = '5' - 2; // '5' is converted to the number 5
console.log(result); // Prints: 3

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 the values to strings.

let greeting = 'The number is ' + 7; // 7 is converted to the string '7'
console.log(greeting); // Prints: The number is 7

Here, the number 7 is converted to the string '7' in order to concatenate it with 'The number is '.

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 in order to compare the two values.

Logical Operators

Logical operators (&&, ||) can perform implicit coercion to convert values to booleans.

console.log('' || 'Hello'); // Prints: Hello

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

Function Conversion

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 ('text') {
   console.log('Always true'); // Executes
}

if (0) {
   console.log('Never true'); // Does not execute
}

Eh… don’t do that, it’s a terrible practice. That’s why boolean values exist.

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 number = Number('123'); // Explicit conversion to number
console.log(number); // Prints: 123

You can also use parseInt() or parseFloat() to convert strings to integers or floating-point numbers, respectively.

let integer = parseInt('123', 10); // Convert to integer
let float = parseFloat('123.45'); // Convert to float

Conversion to String

Use String() to convert a number or any other value to a string.

let str = String(123); // Explicit conversion to string
console.log(str); // Prints: '123'

The .toString() method can also be used to convert numbers and other types to strings.

let num = 123;
let str = num.toString(); // Explicit conversion to string
console.log(str); // Prints: '123'

Conversion to Boolean

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

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

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 not equal to 0
Number (0)="0"false
Boolean (true)1"true"=
Boolean (false)0"false"=
null0"null"false
undefinedNaN"undefined"false

Conversion to Number

  • Strings that contain numbers are converted to those numbers.
  • While non-numeric strings result in NaN.
  • true converts to 1.
  • false and null convert to 0.
  • undefined converts to NaN.

Conversion to String

  • All types can be converted to a textual representation using their value (for example, 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 is important to keep the following tips in mind:

Use strict comparison operators (=== and !==) instead of loose 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') {