Today I Learned - Rocky Kev

TIL JS Coercion

POSTED ON:

TAGS:

Javascript does a lot of stuff behind-the-scenes.

Coercion is one of them.

Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.

For example:

const valueA = "100" + 1; // 1001 -- string type
const valueB = 100 * "2" // 200 -- number type

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.

This is all done behind the scene. There's actual logic to decide when things happen.

Coercion

In the ECMAScript documentation, you can force types to switch.

LINK: https://262.ecma-international.org/9.0/#sec-abstract-operations

For example, with toBoolean, It literally just uses a lookup table.

toString & toNumber are other common ones.

Coercion behind the scenes

Well, string literals are "literally" using coercion!

var numStudents = 16;

// this is Coercion
console.log(`There are ${numStudents} students.`); // There are 16 students

// this is explicit Coercion

// 'join' forces things to become strings. Don't do this.
console.log(`There are ${[numStudents].join('')} students.`); // There are 16 students

// A function on a primitive? wtf?
console.log(`There are ${numStudents.toString()} students.`); // There are 16 students

// A clearer way
console.log(`There are ${String(numStudents)} students.`); // There are 16 students

REFERENCE:
Kyle Simpson's Deep JS Frontend Master's course


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.