DEV Community

Cover image for The curious case of mathematical precision & legacy JS vs ES6.
Arun Prakash Pandey
Arun Prakash Pandey

Posted on

The curious case of mathematical precision & legacy JS vs ES6.

Troubles faced with precision

0.3 - 0.2 !== 0.2 - 0.1
Enter fullscreen mode Exit fullscreen mode

because computers understand Base-2 i.e. binary. To store a decimal number, it must be converted to base.

The Problem:

  • The number 0.1 in decimal is a repeating fraction in binary.
  • 0.1 in binary is 0.00011001100110011... repeating forever.
  • Because the computer can allocate a finite number of bits (the 52-bits out of 64, 1 bit (0 for positive, 1 for negative), and 11 bits for storing numbers to represent the numbers upto scale/power of 2) for this purpose, it eventually has to "cut off" the repeating fraction. It rounds it to the nearest representable binary value.

isNaN() vs Number.isNan()

console.log(Number.isNaN(undefined)); //from ES6
// false 
console.log(isNaN(undefined)) //global isNan() from old Js
// true
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Number.isNaN() is a strict check. It does not perform any type coercion.
  • The global isNaN() function was created in the early days of JavaScript when the language was much more "forgiving." It doesn't check if the value is NaN; it performs type coercion.

charCodeAt() vs codePointAt()

This history:

  • JavaScript strings are encoded in UTF-16. When UTF-16 was designed, it was believed that 16 bits (65,536 values) would be enough to hold every character in every language.
  • As reality hits hard, it was not enough for supporting rare characters (like Emojis, historical scripts, complex mathematical symbols).

The Solution:

  • The system introduced Surrogate Pairs, by combining two 16-bit code units.
charCodeAt() //old Js
codePointAt() // ES6
Enter fullscreen mode Exit fullscreen mode

To be continued...

Top comments (0)