Convert Decimal to Octal in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Base conversion

What You’ll Learn

Decimal-to-octal conversion turns a base-10 integer into a base-8 digit string (digits 0–7). This tutorial covers remainders, recursion, built-ins, a live preview, worked JavaScript examples, edge cases, and complexity.

Powers of Eight

Base 8

Each digit is a coefficient on 1, 8, 64, 512…

Remainders

n % 8

Collect digits LSD-first, then reverse for MSD-first output.

Recursion

MSB first

Recurse on Math.floor(n / 8) before appending n % 8 — no reverse array.

Handle Zero

Special case

Return "0" — a plain while n > 0 loop would print nothing.

Binary Link

3 bits each

One octal digit equals exactly three binary bits.

O(log n)

Complexity

About log8 n digits for nonnegative n.

Introduction

Decimal-to-octal conversion writes a nonnegative integer using digits 0–7 only. Classic example: 57 = 7 × 8 + 1 → octal 71.

The classroom method divides by 8 and stacks remainders (LSD first), then reverses. Recursion or n.toString(8) can produce the same string more directly.

Why it matters?

It generalizes the binary conversion pattern, trains base-8 place value, and links neatly to binary triplets.

Key Highlights

LSD First

First remainder is the rightmost digit.

Reverse to Print

MSD-first output needs a reverse (or recursion).

Zero Guard

Always return "0" for input 0.

3 Binary Bits

Each octal digit packs three bits.

In short: repeatedly take n % 8 and Math.floor(n / 8), reverse the digits (or recurse MSD-first), and special-case zero.

📝 Problem & Approach

Given a nonnegative integer n, return its octal representation as a string (minimal digits, no leading zeros except for 0).

JavaScript
// 57 → remainders 1, 7 → reverse → "71"
// 64 → "100"
// 0  → "0"

Inputs & Outputs

ItemTypeDescription
nnumberNonnegative integer (define policy for negatives).
Return / printstringOctal digits as a string, e.g. "71".

Minimal workflow

Pseudocode
function decimalToOctal(n) {  // n >= 0
  if (n === 0) return "0";
  const digits = [];
  while (n > 0) {
    digits.push(String(n % 8));
    n = Math.floor(n / 8);
  }
  return digits.reverse().join("");
}

Method comparison

MethodIdeaNotes
Remainder + reverseCollect n % 8, then reverseBest classroom / interview explanation
Recursive MSD-firstRecurse on Math.floor(n / 8), then append n % 8No reverse list
Built-inn.toString(8)Idiomatic production JavaScript

⚡ Quick Reference

GoalPattern
Next digitn % 8
Drop digitn = Math.floor(n / 8)
MSD-first outputdigits.reverse() or recurse first
Zero caseif (n === 0) return "0"
Built-inn.toString(8)
Binary grouping3 bits ↔ 1 octal digit

📋 Remainder vs Recursion vs Built-in

Same octal string — different clarity and interview signaling.

Remainder
% 8 + reverse

Shows place-value / division clearly

Recursion
MSD first

Call stack delays lower digits naturally

Built-in
toString(8)

Shortest production style

Interview tip
remainders first

Explain loops, then mention built-ins

Context

When This Problem Shows Up

Reach for decimal-to-octal drills when base-8 conversion and binary grouping matter.

  1. Interview warm-ups

    Same remainder pattern as binary, with digits 0–7.

  2. Teaching binary triplets

    Octal is a compact way to read binary in groups of three.

  3. Unix / permission lore

    Classic chmod modes are often written in octal.

  4. Gateway to hex

    Same idea with base 16 and digit alphabet 0–9A–F.

  5. Not for floats alone

    Fractional octal needs a different place-value story after the point.

Key benefit: one short problem that generalizes binary conversion and connects neatly to 3-bit grouping.

🔮 Live Preview

Nonnegative integers in JavaScript safe range, using toString(8).

Try 0, 8, 57, or 64. Negatives are not supported in this widget.

Live result
Press “Show octal” to convert.

Examples Gallery

Three complete JavaScript programs with Try it Yourself editors — remainder + reverse, recursive MSD-first, and built-in formatting. Click View Output to reveal sample console results.

📚 Getting Started

Classic divide-by-eight approach — collect, then reverse.

Example 1 — Divide by Eight and Reverse

Collect remainder digits LSD-first, then reverse to print MSD-first.

JavaScript
function decimalToOctal(n) {
  if (n === 0) {
    return "0";
  }
  const digits = [];
  while (n > 0) {
    digits.push(String(n % 8));
    n = Math.floor(n / 8);
  }
  return digits.reverse().join("");
}

console.log("Octal equivalent:", decimalToOctal(57));
console.log("Octal equivalent:", decimalToOctal(0));

How It Works

Remainders come from right to left, so reversing is required for proper left-to-right octal display.

⚡ Recursive Style

No explicit reversal list — the call stack prints higher digits first.

Example 2 — Recursive MSD-First Print

Recurse on Math.floor(n / 8), then append n % 8.

JavaScript
function printOctalRecursive(n) {
  if (n < 8) {
    return String(n);
  }
  return printOctalRecursive(Math.floor(n / 8)) + String(n % 8);
}

console.log("57 in octal:", printOctalRecursive(57));
console.log("0 in octal:", printOctalRecursive(0));

How It Works

The call stack naturally delays lower digits until higher digits are printed — base case n < 8 returns a single digit (including 0).

🚀 Idiomatic JavaScript

Same answer with built-ins — great after you know the algorithm.

Example 3 — Using toString(8)

Minimal digits, plus a quick binary-triplet check.

JavaScript
function toOctalBuiltin(n) {
  if (n < 0) {
    throw new Error("This helper expects a nonnegative integer");
  }
  return n.toString(8);
}

console.log(toOctalBuiltin(57));
console.log(toOctalBuiltin(0));
console.log((57).toString(8));       // same as above
console.log((57).toString(2));      // binary of 57
// 71 octal ↔ 111 001 binary (7=111, 1=001)

How It Works

n.toString(8) is the cleanest minimal-digit conversion. Grouping binary 111001 as 111 001 recovers octal digits 7 and 1.

🧠 How the Algorithm Converts

1

Handle zero

If n === 0, return "0" immediately.

Guard
2

Collect digits

Append n % 8, then set n = Math.floor(n / 8) until n becomes 0.

Loop
3

Reverse / join

Reverse the list (or have recursed MSD-first) and join into a string.

Format
=

Octal string

Return the MSD-first digit string — that is the base-8 form of n.

🔎 Worked Walkthrough — n = 57

Trace the remainder method. Digits collect LSD-first, then reverse.

nn % 8Math.floor(n / 8)digits so far
5717[1]
770[1, 7]

Reverse → 71. Check: 7 × 8 + 1 = 57.

Use Cases

Where decimal-to-octal conversion shows up beyond the interview prompt.

1. Interview Warm-Ups

Generalizes binary conversion to another base.

Example: write decimalToOctal(n).

2. Teaching Binary Groups

Map each octal digit to three bits.

Example: 7 ↔ 111.

3. File Permission Modes

Unix modes are often written in octal.

Example: 755, 644.

4. Gateway to Hex

Same remainder idea with base 16.

Example: n % 16 + digit map.

5. Round-Trip Practice

Convert to octal then back with parseInt(s, 8).

Example: assert parseInt(octal, 8) === n.

6. Recursion Practice

MSD-first print is a clean recursion demo.

Example: recurse then append remainder.

Pro Tip: say “first remainder is the LSD” before coding — same tip as for binary, with base 8.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Familiar Pattern

    Same structure as decimal-to-binary — only the divisor changes.

  2. 2. Binary Shortcut

    Three-bit groups make mental conversion fast.

  3. 3. Easy Built-in

    n.toString(8) keeps application code short after the theory.

  4. 4. Clear Complexity

    O(log8 n) digits are easy to argue in interviews.

Pro Tip: after binary, ask yourself “what changes for octal?” — answer: divisor 8 and digit range 0–7.

Usage Tips

Small habits that keep decimal-to-octal solutions interview-ready.

  1. 1. Special-Case Zero

    Return "0" before the remainder loop.

  2. 2. Say LSD First Out Loud

    Then reverse (or recurse) for MSD-first print.

  3. 3. Spot-Check 57 and 8

    Expect 71 and 10 as golden tests.

  4. 4. Mention Binary Triplets

    Shows you understand why octal exists historically.

  5. 5. Mention Built-ins Second

    Show the loop first; then n.toString(8).

Pro Tip: round-trip with parseInt(octal, 8) to catch reverse mistakes instantly.

Common Pitfalls

Mistakes that commonly break decimal-to-octal solutions.

  1. 1. Forgetting to Reverse

    Printing remainders in collection order reverses the digits.

    → Reverse the list (or recurse MSD-first).

  2. 2. Empty Output for Zero

    while n > 0 never runs when n is 0.

    → Return "0" explicitly.

  3. 3. Dividing by 10 by Habit

    Copying a decimal digit-extraction loop is a common slip.

    → Use % 8 and Math.floor(n / 8).

  4. 4. Confusing Octal with Hex Prefixes

    Some languages prefix octal with 0o; JavaScript uses 0o only in numeric literals, not in toString(8) output.

    → Use n.toString(8) for digit-only strings.

  5. 5. Deep Recursion on Huge n

    Very large integers can hit recursion limits.

    → Prefer the iterative remainder method for huge values.

Edge Cases

Set rules for negative numbers early; many beginner versions accept only nonnegative input.

Zero

n == 0

Without explicit handling, loop-based code can return empty output.

Negative

Choose policy

Either reject negatives or define representation convention clearly.

Digits

Only 0 to 7

Octal never uses digits 8 or 9.

Powers of 8

8, 64, 512

Become 10, 100, 1000 — good reverse checks.

Single digit

n in 1…7

Already octal — return unchanged as a string.

Recursion

Deep calls

For extremely large integers, iterative methods avoid recursion depth concerns.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Binary triplets. One octal digit = three binary bits (7 ↔ 111).
  • Uniqueness. Every nonnegative integer has a unique octal form without leading zeros (except 0).
  • Inverse. Octal-to-decimal uses place values or parseInt(s, 8).
  • Digit count. Positive n needs about floor(log8 n) + 1 octal digits.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 0 → 0
  • 57 → 71
  • 64 → 100

2. Match all three styles

  • Remainder, recursive, toString(8)
  • Assert identical strings

3. Binary triplets

  • Convert 57 to binary
  • Group as 111 001 ↔ 71

4. Round-trip

  • Convert to octal then back
  • Use parseInt(s, 8)

Notes

  • Idea: repeatedly take % 8 and divide by 8.
  • Code: handle zero explicitly, then reverse collected digits.
  • Bonus: one octal digit equals three binary bits.
  • State O(log8 n) time for nonnegative n.

Quick Takeaway: collect n % 8 remainders, reverse them (or recurse MSD-first), and special-case zero.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Remainder + reverse listO(log8 n)O(log8 n)
Recursive printO(log8 n)O(log8 n) stack
Built-in toString(8)Typically O(d) digitsO(d) output

Here n is nonnegative and d is the number of octal digits.

Wrap Up

🎉 Conclusion

Decimal-to-octal conversion is the binary remainder pattern with divisor 8: collect digits LSD-first, reverse for MSD-first output, and handle zero. Recursion and toString(8) are strong follow-ups once the theory is clear.

Practice the three examples above, then continue to Disarium numbers for a digit-power warm-up.

Always special-case 0, remember the first remainder is the LSD, and mention the 3-bit binary link.

💡 Best Practices

✅ Do

  • Handle n == 0 first
  • Explain LSD-first remainders
  • Reverse (or recurse) for MSD output
  • Test 0, 57, and 64
  • Mention toString(8) as a shortcut

❌ Don’t

  • Forget the reverse step
  • Return empty string for 0
  • Divide by 10 by accident
  • Leave negatives undefined
  • Assume toString(8) adds a 0o prefix (it does not)

Key Takeaways

Knowledge Unlocked

Five things to remember about decimal to octal

Convert base 10 the interview-friendly way.

5
Core concepts
8 02

Base

Divide by 8

Math
0 03

Zero

Return "0"

Guard
3 04

Binary

3 bits each

Link
O 05

Complexity

O(log n)

Analysis

❓ Frequently Asked Questions

Octal is base 8. The remainder n % 8 gives the least significant octal digit, and Math.floor(n / 8) removes that digit for the next step.
Remainders are generated from least significant digit to most significant digit. Reversing prints the standard left-to-right octal form.
A plain while (n > 0) loop does not run, so you must special-case 0 and return '0'.
Yes. n.toString(8) returns minimal octal digits for nonnegative integers. Learning the manual method still helps interviews.
One octal digit equals three binary bits. For example, octal 7 corresponds to binary 111.
For nonnegative n, remainder method uses O(log8 n) digits, which is O(log n).
Only 0 through 7. Digits 8 and 9 never appear in a valid octal string.
It prints higher digits first by recursing on Math.floor(n / 8) before appending n % 8, so no explicit reverse is needed.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Did you Know? 🔊

Each octal digit corresponds to a block of three binary bits, which is why Unix file modes and some literals are still written in base eight.

Continue to Disarium Number

Learn how to check whether a number equals the sum of its digits raised to their positional powers.

Disarium number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful