Octal & Binary Literals in JavaScript

Understanding Octal & Binary Literals in JS 🧠

In JavaScript, numbers are not limited to the familiar decimal system (base 10). You can also write numbers in binary (base 2) or octal (base 8) notation. This can be very useful when working with low-level operations, bitwise calculations, or hardware-related tasks.

Binary Literals 🔢

Binary numbers use only 0 and 1. In modern JavaScript (ES6+), you can define a binary literal by prefixing the number with 0b or 0B.

Binary Literal Example

const binaryNum = 0b1010; // equals 10 in decimal
console.log(binaryNum); // Output: 10

Note

💡 Binary literals are especially useful for bitwise operations and when dealing with flags or masks.

Octal Literals 🔢

Octal numbers use digits from 0 to 7. In ES6+, you can write octal literals with a 0o or 0O prefix.

Octal Literal Example

const octalNum = 0o17; // equals 15 in decimal
console.log(octalNum); // Output: 15

Note

⚠️ Avoid using the old-style octal notation (numbers starting with 0, e.g., 017) in strict mode—it’s deprecated and may throw errors.

Quick Comparison Table 📊

LiteralExampleDecimal Value
Binary0b101010
Octal0o1715

Mixing with Other Operations ⚡

You can use octal and binary literals in arithmetic and bitwise operations just like decimal numbers:

Binary & Octal Operations Example

const bin = 0b1100; // 12
const oct = 0o10; // 8

console.log(bin + oct); // Output: 20
console.log(bin & oct); // Output: 8 (bitwise AND)
Practical Use Cases 💼
  • Working with bit flags in configuration settings.
  • Interfacing with hardware or memory-mapped devices.
  • Writing low-level algorithms that require bit manipulation.
>>"Understanding different number systems opens up a new level of precision and control in programming." 🔥

For more details on numeric literals in JS, check the official MDN documentation.