In JavaScript, number literals can be represented in various numeral systems using different prefixes. Here are the commonly used prefixes for different numeral systems:
- Decimal: No prefix is required for decimal numbers.
For example:
42,3.14,10. - Binary:
The
0bor0Bprefix is used to represent binary numbers. Binary numbers consist of only0and1. For example:0b1010represents the binary number1010, which is equivalent to10in decimal. - Octal:
The
0oor0Oprefix is used to represent octal numbers. Octal numbers consist of digits from0to7. For example:0o77represents the octal number77, which is equivalent to63in decimal. - Hexadecimal:
The
0xor0Xprefix is used to represent hexadecimal numbers. Hexadecimal numbers consist of digits from0to9and lettersAtoF(oratof) representing values from10to15. For example:0xFFrepresents the hexadecimal numberFF, which is equivalent to255in decimal.
Here are some examples illustrating the use of different prefixes:
const decimal = 42; // Decimal number
const binary = 0b1010; // Binary number (10 in decimal)
const octal = 0o77; // Octal number (63 in decimal)
const hexadecimal = 0xff; // Hexadecimal number (255 in decimal)
console.log(decimal); // Outputs: 42
console.log(binary); // Outputs: 10
console.log(octal); // Outputs: 63
console.log(hexadecimal); // Outputs: 255It's important to note that these prefixes are used only for number literals. Once a number is assigned to a variable, the numeral system is not associated with the value itself. Therefore, you can perform arithmetic operations or manipulate the numbers regardless of the numeral system used in the original literal representation.
Additionally, these prefixes are not limited to BigInt or specific number types. They can be used with regular numbers (number) as well. However, it's worth mentioning that binary literals and the BigInt type were introduced in more recent versions of JavaScript, so their support may vary across different environments or older browsers.