Coercion

Type coercion is the automatic (or implicit) conversion of values from one data type to another.

Essential:

github.com/getify/You-Dont-Know-JS

Description:

As previously introduced, type coercion refers to the automatic conversion of values from one data type to another, typically performed during operations or comparisons involving different data types (such as strings to numbers, for instance). By using Type Coercion, JavaScript attempts to make the data types compatible to complete the operation or comparison.

Table of Contents

  1. 1. Introduction
  2. 2. ToString
  3. 3. ToNumber
  4. 4. ToBoolean
  5. 5. Equality
  6. 6. Documentation
  7. 7. Related notes

1. Introduction

A type can be converted in two different ways:

Description
Type castingExplicitly converting a value from one type to another. Occurs in statically typed languages at compile time. TypeScript example: const myVar = otherVar as string.
CoercionOccurs in dynamically typed languages, like JavaScript, at runtime. It can happen in 2 different ways:
    ▪ Explicit: the intent is to obviously convert a value from one type to another.
    ▪ Implicit: type conversion occurs as a side-effect of some operation.

Let’s see some examples:

Example:

Note: Whenever coercion occurs, 1 or more internal operations, known as abstract operations, are performed. It always results in a primitive.

Translation from one language to another visual asset.
Metaphor time:

Coercion is somehow similar to translating words from one language to a similar one, like Spanish and Italian. If we were to translate the word ”noche” (night) to Italian, as translators, we would look at all the available Italian words until we could find the one best matching the Spanish word’s meaning: in this case, ”notte“.

In JavaScript, the translator would be the engine, the word, a value, and the languages, JavaScript’s types. Now, imagine that the engine needs to coerce a value from a string to a boolean. The engine would look at the available “words” (values) in the boolean “language” (type). Sadly, in this case, there are only two options: true or false, and whichever is selected, a lot of the string’s meaning would be lost in translation, as it happens too in our own adaptations.

Explicit Coercion

To explicitly coerce a value to a string, number, or boolean, remember to use the built-in native contructors. In this case, the new keyword isn’t used, so an object wrapper isn’t created.

Example:


2. ToString

The ToString abstract operation rules are:

    ▪ null becomes ”null"

    ▪ undefined becomes "undefined"

    ▪ true becomes "true"

    ▪ number: 1 becomes "1".

Example:


3. ToNumber

The ToNumber abstract operation rules are:

    ▪ true becomes 1

    ▪ false becomes 0

    ▪ undefined becomes NaN

    ▪ null becomes 0

    ▪ string: "1" becomes 1, "a" becomes NaN


To coerce an Object value:

StepDescription
1.The ToPrimitive() abstract operation will check if the object has a valueOf() method.
    ▪ If it exists and it returns a primitive value, that value will be used.
    ▪ If it doesn’t exist, but toString() does, its return value will be used.
    ▪ If neither exist or don’t return a primitive, a TypeError is thrown.
2.The primitive value will be coerced as per the ToNumber rules above.

Example:

parseInt

parseInt(..) can be used to get a numeric value out of a string containing non-numeric characters. It parses left-to-right and stops when a non-numeric value is found.

const a = “42px”;Outputs
console.log(Number(a)); // Output: NaN
console.log(parseInt(a)); // Output: 42

4. ToBoolean

The ToBoolean abstract operation rules are:

    ▪ undefined becomes false

    ▪ null becomes false

    ▪ +0, -0, and NaN becomee false

    ▪ "" becomes false

    ▪ all other values become true

var myVar = 1;Outputs
console.log(Boolean(myVar)); // Output: true
console.log(!!myVar); // Output: true

Implicit Coercion

Expression operations that are implicitly coerced to a boolean:

    ▪ The test expression in an if (..) statement.

    ▪ The test expression (2nd clause) in a for ( .. ; .. ; .. ) header.

    ▪ The test expression in while (..) and do..while(..) loops.

    ▪ The test expression (1st clause) in a ? : ternary expression.

    ▪ The left-hand operand to the || and && operators.


5. Equality

When comparing 2 values for equality, commonly used operators are:

    ▪ loose equality: ==

    ▪ strict equality: ===

Example:


6. Documentation

If you found this useful, please refer You don’t know JavaScript’s Chapter 4: Coercion - and don’t forget to have a look at these useful resources as well:

    ▪freeCodeCamp

    ▪HackerNoon


All Notes: