TIL JS Coercion
POSTED ON:
TAGS: javascript edge-cases ecmascript
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: javascript