Numeric Separator in JavaScript
🧠 What is the Numeric Separator?
The numeric separator (underscore `_`) is a feature introduced in ES2021 that improves number readability by allowing you to visually group digits, much like commas in real-world numbers.
>>“Just because computers can read long numbers doesn't mean you should!” 💡
📌 Why Use Numeric Separators?
- ✅ Makes large numbers easier to read
- ✅ No effect on the actual numeric value
- ✅ Supported in modern browsers and Node.js (v12.5+)
✨ Basic Syntax
You can insert an underscore _ between any digits in a number:
Examples of Numeric Separators
let billion = 1_000_000_000;
let bytes = 64_000_000;
let creditCard = 1234_5678_9012_3456;
console.log(billion); // 1000000000
console.log(bytes); // 64000000
console.log(creditCard); // 1234567890123456📐 Where Can You Use It?
- ✅ Integer literals
- ✅ Binary, octal, and hexadecimal numbers
- ✅ Decimal literals (but not at the start or end of decimals)
Binary, Octal, Hex Support
let binary = 0b1010_1011_1100;
let octal = 0o1234_5670;
let hex = 0xAB_CD_EF;
console.log(binary); // 2748
console.log(octal); // 273912
console.log(hex); // 11259375⚠️ Invalid Uses
There are rules to where you can place underscores:
- ❌ Not at the beginning or end of a number
- ❌ Not adjacent to a decimal point
- ❌ Not in numeric strings (e.g., "1_000")
Invalid Examples
let wrong = _1000; // ❌ SyntaxError
let alsoWrong = 1000_; // ❌ SyntaxError
let notOk = 1_.000; // ❌ SyntaxError
let stringy = "1_000"; // Treated as a string, not a numberNote
🧠 Numeric separators are purely for code readability. They do not affect the actual value.
✅ Use Cases
- 💵 Financial numbers (e.g., 10_000_000)
- 🧮 Byte sizes (e.g., 64_000_000)
- 📟 Binary/hex manipulation (e.g., 0b1111_0000)
- 💳 Formatting account/credit card numbers (in code)
📚 Resources
🔚 Summary
- Use _ inside numbers to improve readability
- Works with decimal, binary, octal, and hex
- Can’t be used next to dots or at the start/end
>>“Readable code is reliable code. Use separators to let your numbers breathe.” 🧘