Binary (0b) and octal (0o) literals: clear bits (ES2015)
What you’ll learn
Section titled “What you’ll learn”- How to write binary (
0b1010) and octal (0o755) numbers, and why legacy0755fails in strict mode. - How
Number(),parseInt()andtoString()convert between strings and these bases. - How to use them for permission bitmasks and Unix file modes.
Summary
Section titled “Summary”TL;DR: 0b (or 0B) followed by 0 and 1 digits is a binary literal; 0o (or 0O) followed by digits 0 to 7 is an octal literal. Both produce an ordinary number, exactly like 0x hex literals. Add n for a BigInt. They replace parseInt(str, 2) workarounds and the confusing legacy octal form.
They were added in ECMAScript 2015 and are supported by every current browser and server runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”Before ES2015 JavaScript had hexadecimal literals (0xff) but no binary syntax, so bit patterns were written in hex, in decimal, or parsed from a string at run time. Octal existed only as a non-standard leading zero: 0755 meant 493. A stray zero silently changed a value, and a number such as 0855 quietly stayed decimal because 8 is not an octal digit.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23.
// Before ES2015: hex had a prefix, binary had none, and octal was a leading zero.const flagsOld = parseInt('1011', 2); // binary through a stringconst modeOld = parseInt('644', 8); // octal through a string (0644 was legacy octal syntax)
// ES2015: binary (0b) and octal (0o) literals, checked at parse time.const flags = 0b1011;const mode = 0o644;console.log(flagsOld, flags); // 11 11console.log(modeOld, mode); // 420 420console.log(0B11, 0O17, 0xff); // uppercase prefixes work too: 3 15 255How it works
Section titled “How it works”// The literal is just a Number: the base is not remembered.console.log(0b1010 === 10, 0o12 === 10, typeof 0o12); // true true numberconsole.log((10).toString(2), (493).toString(8)); // 1010 755
// Combined with numeric separators (ES2021) and BigInt (ES2020)console.log(0b1111_0000, 0o7_5_5, 0b1n << 63n);
// Invalid digits and legacy forms are compile-time errorsconst sources = [ '0b102', // digit 2 is not binary '0o8', // digit 8 is not octal '"use strict"; 0755', // legacy octal is banned in strict mode (and in modules) '"use strict"; 089', // so is a leading zero on a decimal literal '0755n', // no legacy octal BigInts];for (const src of sources) { try { new Function(src); console.log(src.padEnd(22), 'ok'); } catch (e) { console.log(src.padEnd(22), `${e.name}: ${e.message}`); }}
// Sloppy-mode scripts still accept the legacy forms, with a trap:console.log(new Function('return [0755, 0855]')()); // [ 493, 855 ]
// Strings: Number() understands the prefixes, parseInt() does notconsole.log(Number('0b101'), Number('0o17'), Number('0x1f')); // 5 15 31console.log(parseInt('0b101'), parseInt('0o17'), parseInt('0x1f')); // 0 0 31console.log(parseInt('101', 2), parseInt('17', 8)); // 5 15console.log(Number('0o19'), Number('0b')); // NaN NaNOutput:
true true number1010 755240 493 9223372036854775808n0b102 SyntaxError: Invalid or unexpected token0o8 SyntaxError: Invalid or unexpected token"use strict"; 0755 SyntaxError: Octal literals are not allowed in strict mode."use strict"; 089 SyntaxError: Decimals with leading zeros are not allowed in strict mode.0755n SyntaxError: Invalid or unexpected token[ 493, 855 ]5 15 310 0 315 15NaN NaNThe details:
- Same type, same value. The prefix only affects how the source is read.
0b1010,0o12,0xaand10are the same number, and nothing records which base you used. To display a value in a base, calltoString(radix)and pad it withpadStart. - Validation at parse time. A digit outside the base (
0b102,0o8) is aSyntaxErrorbefore any code runs, unlikeparseInt, which stops at the first bad character. The messages above are V8’s wording. - Legacy octal. The spec still defines
LegacyOctalIntegerLiteral(0755) andNonOctalDecimalIntegerLiteral(0855,089), but both are early errors in strict mode code, which includes ES modules and class bodies. In sloppy scripts0755is 493 while0855is 855, which is exactly the trap the new prefixes remove. Legacy octal string escapes such as"\101"are banned in strict mode for the same reason (Octal escape sequences are not allowed in strict mode.). - BigInt and separators.
0b...nand0o...nproduce BigInts, and numeric separators may go between digits (0b1010_0001) but not right after the prefix (0b_1) or at the end. - String conversion.
Number()and the unary+accept the0b,0oand0xprefixes in strings.parseInt()only recognizes0x; given'0b101'it parses the leading0and stops. Pass an explicit radix with the digits only, as inparseInt('101', 2).
Realistic example
Section titled “Realistic example”OrdersPortal stores each role’s permissions as a bitmask: one bit per permission, written as a binary literal so the bit positions are visible in the code. Its nightly order export is written with the Unix mode 0o640 (owner read/write, group read, others nothing), the same digits you would pass to chmod.
// perms.mjs - OrdersPortal: role permissions as a bitmask, export files with an octal mode.import { writeFileSync, chmodSync, statSync, mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';
export const Permission = Object.freeze({ VIEW_ORDERS: 0b0000_0001, EDIT_ORDERS: 0b0000_0010, ISSUE_REFUNDS: 0b0000_0100, EXPORT_DATA: 0b0000_1000, MANAGE_USERS: 0b0001_0000,});
export const Roles = Object.freeze({ support: Permission.VIEW_ORDERS | Permission.ISSUE_REFUNDS, analyst: Permission.VIEW_ORDERS | Permission.EXPORT_DATA, admin: 0b0001_1111,});
export const can = (mask, permission) => (mask & permission) === permission;export const describe = (mask) => Object.keys(Permission).filter((name) => can(mask, Permission[name]));export const show = (mask) => '0b' + mask.toString(2).padStart(5, '0');
for (const [role, mask] of Object.entries(Roles)) { console.log(role.padEnd(8), show(mask), describe(mask).join(', '));}console.log(can(Roles.support, Permission.EXPORT_DATA)); // false
// Grant and revoke with bitwise operatorslet custom = Roles.support | Permission.EXPORT_DATA;custom &= ~Permission.ISSUE_REFUNDS;console.log(show(custom), describe(custom));
// Write an export readable by owner and group only: rw-r----- is 0o640.const dir = mkdtempSync(join(tmpdir(), 'ordersportal-'));const file = join(dir, 'orders-2026-11.csv');writeFileSync(file, 'id,total\n1001,45.99\n');chmodSync(file, 0o640);console.log((statSync(file).mode & 0o777).toString(8)); // 640Output (Linux; Windows ignores most mode bits):
support 0b00101 VIEW_ORDERS, ISSUE_REFUNDSanalyst 0b01001 VIEW_ORDERS, EXPORT_DATAadmin 0b11111 VIEW_ORDERS, EDIT_ORDERS, ISSUE_REFUNDS, EXPORT_DATA, MANAGE_USERSfalse0b01001 [ 'VIEW_ORDERS', 'EXPORT_DATA' ]640chmodSync is used instead of the mode option of writeFileSync because the process umask can clear bits from the mode option, which would make the output differ between machines.
Common mistakes
Section titled “Common mistakes”- Writing file modes in decimal.
chmodSync(file, 640)sets mode0o1200, notrw-r-----. Always write0o640. - Calling
parseInton a prefixed string.parseInt('0b101')is0. UseNumber('0b101'), or strip the prefix and pass a radix. - Relying on the leading zero.
0755fails in modules and strict code and means something different from0855in sloppy code. Search old code for\b0[0-9]+\bwhen migrating it to modules. - More than 32 flags. JavaScript’s bitwise operators convert to 32-bit integers, so
0b1 << 32is1, not 2^32, and bit 31 makes the result negative. Above 31 flags, use BigInt literals and operators (0b1n << 40n) or aSetof names. - Expecting the base to survive.
JSON.stringify({ mode: 0o640 })is{"mode":416}. Format withtoString(8)when a human or another tool expects octal.
When to use it and when not to
Section titled “When to use it and when not to”| You are writing | Prefer | Example |
|---|---|---|
| Individual bits, flags, masks | Binary 0b |
0b0000_0100 |
Unix permissions, umask |
Octal 0o |
0o640 |
| Bytes, colors, memory addresses, Unicode code points | Hex 0x |
0xff, 0x1F600 |
| Quantities, money, counts | Decimal | 1_000 |
| A wide bit pattern | Hex | 0xFFFF_0000 is shorter than its 32-digit binary form |
Use binary when someone reading the code needs to see each bit, and octal only where the domain already thinks in octal. For a long mask, hex is usually easier to read than binary.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, binary and octal literals are supported in Chrome 41, Edge 12, Firefox 25, Safari 9 (including iOS), Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported them. Separators inside them need ES2021 support, and the n suffix needs BigInt (ES2020).
TypeScript: when targeting ES5, TypeScript rewrites 0b1011 and 0o644 as 11 and 420, so the output runs in pre-ES2015 engines. It rejects the legacy form at every target: TS1121: Octal literals are not allowed. Use the syntax '0o755'. (checked with TypeScript 6.0.3).
Interview questions
Section titled “Interview questions”1. What does 0o17 + 0b11 + 0x1 evaluate to, and what type is it?
19, a number: 15 + 3 + 1. The prefixes only change how the literal is read; the value is an ordinary Number.
2. Why does parseInt('0b101') return 0 while Number('0b101') returns 5?
parseInt only auto-detects the 0x prefix. It reads 0, hits b, and stops. Number() uses the full numeric-literal grammar for strings, which includes 0b and 0o.
3. Senior scenario: you inherit a permissions system whose flags are decimal constants (1, 2, 4, … 1073741824) and the product team wants 40 more permissions. What do you do?
Rewrite the constants as binary literals or 1 << n so bit positions are obvious, and add a test that every flag is a distinct single bit. Then recognize the 32-bit limit: JavaScript’s bitwise operators truncate to 32 bits and bit 31 is the sign bit, so 40 more flags won’t fit. Options are BigInt masks (1n << 40n), several 32-bit words, or storing permissions as a set of string names, which is easier to audit and evolve. Check how the mask is persisted, because a database integer column or JSON consumer may also cap the width.
Key takeaways
Section titled “Key takeaways”0band0o(ES2015) write binary and octal numbers; the result is a normal Number, or a BigInt withn.- Invalid digits are syntax errors; legacy
0755octal is banned in strict mode and modules. Number()understands the prefixes in strings;parseInt()needs a radix and no prefix.- Bitwise operators work on 32 bits, so use BigInt for wider masks.
Related pages
Section titled “Related pages”- Numeric separators: grouping digits as in
0b1010_0001. - BigInt:
0b...nand0o...nliterals and masks wider than 32 bits. - Exponentiation operator: computing powers of two instead of writing them out.
- String.prototype.padStart: zero-padding
toString(2)output. - Operators: the bitwise operators used with masks.
- Type coercion: how strings become numbers.
Official references
Section titled “Official references”- ECMAScript Language Specification, Numeric Literals (current draft;
BinaryIntegerLiteralandOctalIntegerLiteralfirst published in ECMAScript 2015, 6th edition) - ECMAScript 2015 Language Specification (ECMA-262, 6th edition), Numeric Literals
- MDN: Lexical grammar, numeric literals
- MDN: Strict mode, legacy octal literals
- MDN: parseInt()
- Node.js 22:
fs.chmodfile modes