CKTIS / JavaScript
Hexadecimal numeric literals
Write base-16 integers with `0x` or `0X`, and add `n` when you need an exact `BigInt` value rather than a potentially rounded `Number`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
Simplified grammar (brackets mark optional parts):
HexLiteral ::= ("0x" | "0X") HexDigit (["_"] HexDigit)* ["n"]
HexDigit ::= "0"–"9" | "a"–"f" | "A"–"F"Hexadecimal numeric literals write integers in base 16 directly in source code. After 0x or 0X, supply at least one digit from 0–9, a–f, or A–F. Letter case does not change the value: 0xFF === 255 is true.
A single _ can separate two digits. 0xF_F is valid, but 0x_FF, 0xF__F, and 0xFF_ cause a SyntaxError when parsed. These literals have no fractional part or exponent; the e in 0x1e2 is a digit. In -0xFF, - is a separate unary operator.
Without a suffix, the literal gives a Number. Outside the safe integer range, when the magnitude exceeds Number.MAX_SAFE_INTEGER, not every integer is represented exactly. Append lowercase n directly after the last digit to get an exact BigInt instead. Check support for BigInt and numeric separators if you target older runtimes.
"0xFF" is a string, not a numeric literal. Number("0xFF") returns 255, but Number("0xF_F") returns NaN: string conversion does not accept numeric separators. To format a value as hexadecimal text, use (255).toString(16), which returns "ff" without a prefix.
Examples
{
const byte = 0Xf_f;
const rounded = 0x20_0000_0000_0001;
const exact = 0x20_0000_0000_0001n;
console.log(`${byte} ${byte === 255} ${byte.toString(16)}`);
console.log(`${rounded}`);
console.log(`${exact} ${typeof exact}`);
}Result
255 true ff 9007199254740992 9007199254740993 bigint
The first line shows the decimal value, the comparison result, and the hexadecimal text. The next two show that `Number` rounds this large integer while `BigInt` keeps it exact.
Related lessons
- JavaScript · Lesson 2 · Advanced · Version: 4
Sources
- ECMAScript 2024 Language Specification — Numeric Literals
- ECMAScript 2024 Language Specification — Unary − Operator
- ECMAScript 2024 Language Specification — Number.MAX_SAFE_INTEGER
- ECMAScript 2024 Language Specification — ToNumber Applied to the String Type
- Lexical grammar — Hexadecimal
- Number.prototype.toString()