Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Improve Readability with TypeScript Numeric Separators when working with Large Numbers

    Rares MateiRares Matei

    When looking at large numbers in code (such as 1800000) it’s oftentimes difficult for the human eye to quickly see how big the number actually is. TypeScript allows us to use numeric separators to write numbers in a more human readable format (such as 1_800_000), while keeping the generated JavaScript unchanged.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:01 If we had a really large number such as the population of Africa, it would be really hard to tell, at a glance, just how big this number actually is. It would involve a bit of a mental effort.

    00:12 Outside of programming, we usually use the comma separators to make it easier for other humans to read such large numbers. In our case, if we add commas on every third position, we can now instantly tell that it's approximately 1.2 billion.

    00:28 Since TypeScript 2.7, we can now add underscores as numeric separators to the numbers in our code. We'll assign the same number to this constant, but this time I'll add underscores in every third position. This not only makes the code more readable, but it also doesn't affect the final output at all. If we look at the result in JavaScript, we can see that all the underscores got compiled away.

    00:52 TypeScript also doesn't force you to use this feature in a specific way. You can add an underscore after each number, and you can even add them after the decimal point. Compilation won't fail, but it might make the code less readable, so it's up to the developer to use this feature responsibly.

    01:12 For a more real-life example, I'm now going to write an amount input class. I'll create a private static at the top to indicate the maximum amount it supports and amount field of type number to store the actual entered amount.

    01:28 I'll also create a show tooltip method that creates a tooltip and then hides it after a few milliseconds. Finally, I'll add a format million method that takes the current amount and returns the formatted string in millions.

    01:43 Even though we've added just a few underscores to the numbers in this class, because we're working with such large numbers, we've made the overall reading experience a bit more pleasant and the overall cognitive load of someone going through this much lower.