Check Armstrong Number in JavaScript

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Digits & powers

What you’ll learn

  • The Armstrong (narcissistic) condition in base 10: sum of each digit raised to the number of digits.
  • A precise algorithm, pseudocode, and two JavaScript examples: one number and a range scan, plus Try it Yourself links.
  • Why a small integer-style power loop beats Math.pow for exact checks, plus edge cases and complexity.
  • A browser live preview that mirrors the same digit-power rule.

Overview

An Armstrong number equals the sum of its decimal digits, each raised to the power of how many digits it has. Classic example: 153 = 1³ + 5³ + 3³. This tutorial shows how to implement that test in JavaScript, then scan a range.

Two programs

A single-value check (try 153) and a range listing (same idea as 1 to 200 in the reference).

Live preview

See digit count k, the expanded sum of each dk, and the verdict without compiling.

Interview polish

Guards for n ≤ 0, integer powers, overflow notes, and complexity in one place.

Prerequisites

Comfort with loops, integer division, and the modulo operator % is enough to follow the code.

  • JavaScript basics: function, const/let, console.log, and integer division with Math.floor.
  • Extracting the last digit with n % 10 and shifting with n / 10.
  • Optional: comparing this idea to amicable and abundant problems (different rules, same “loop over structure of n” pattern).

What is an Armstrong number?

Let n be a positive integer with k decimal digits. Write those digits as dk-1 … d1 d0 (most significant to least). Then n is an Armstrong number (in base 10) when

dk-1k + … + d1k + d0k = n.

The exponent is always the digit count, not the value of the digit. Same idea generalizes to other bases; here we stay in decimal.

Armstrong sum of (each digit)k = n
Not Armstrong that sum ≠ n
Synonyms narcissistic / PPDI (base 10)

Mathematical definition

Fix base b = 10. If n has k decimal digits ak-1, …, a0 (most significant to least), then n is Armstrong when ak-1k + … + a0k = n.

Three-digit template

For 100 ≤ n ≤ 999, write n = 100a + 10b + c with digits a,b,c. Armstrong means a³ + b³ + c³ = 100a + 10b + c.

Examples: 153, 370, 371, 407 are the only three-digit Armstrong numbers besides the trivial one-digit cases.

Intuition and examples

Count how many digits n has. Peel digits off from the right with % 10 and / 10, raising each peel to that count and adding into a running total. If the total lands back on n, you have an Armstrong number.

Each card shows the digit-power sum with the same exponent k everywhere.

153 Armstrong
Digits
3, so exponent 3
Sum
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Verdict
Equals nArmstrong.
123 Not Armstrong
Digits
3, exponent 3
Sum
1³ + 2³ + 3³ = 1 + 8 + 27 = 36
Verdict
36 ≠ 123 — not Armstrong.
7 Armstrong
Digits
1, exponent 1
Sum
7¹ = 7
Verdict
Every 1–9 works the same way.

Takeaway: the exponent is the length of n in decimal, not “how big the digit feels.”

Live preview

Type a positive integer n. The widget counts decimal digits k, builds the sum of each digit to the kth power, and compares it to n. Caps at 999 999 999 to keep JavaScript arithmetic predictable.

  1. Try 153, 123, or a single digit.
  2. Press Run check (or Enter).
  3. Read the expanded sum line and the verdict.

Use integers n ≥ 1. Very large n may hit precision limits in the browser before the overflow notes in the tutorial body matter.

Live result
Press “Run check” to see digit powers and the verdict.

Algorithm

Goal: decide whether a given n is an Armstrong number in base 10.

Validate n

If n ≤ 0, return false (or follow your problem’s convention explicitly).

Count digits k

Copy n to a temporary variable and repeatedly divide by 10 until it becomes 0, counting iterations.

Accumulate digit powers

Walk digits again with % 10 and / 10. Add digit^k to a running sum using exact integer exponentiation.

Compare

If the sum equals the original n, return true; otherwise false.

📜 Pseudocode

Pseudocode
function digitCount(n):
    k ← 0
    t ← n
    while t > 0:
        k ← k + 1
        t ← floor(t / 10)
    return k

function sumDigitPowers(n, k):
    sum ← 0
    t ← n
    while t > 0:
        d ← t mod 10
        sum ← sum + (d to the power k)   // integer power
        t ← floor(t / 10)
    return sum

function isArmstrong(n):
    if n <= 0:
        return false
    k ← digitCount(n)
    return sumDigitPowers(n, k) = n
1

Check a single number (program with explanation)

Uses a small intPow helper so every step uses integer-style multiplication—no Math.pow rounding surprises for typical interview inputs.

JavaScript
function intPow(base, exp) {
  let r = 1;
  for (let e = 0; e < exp; e++) {
    r *= base;
  }
  return r;
}

/** @param {number} number  positive integer */
function isArmstrong(number) {
  if (number <= 0) {
    return false;
  }
  let k = 0;
  let t = number;

  while (t > 0) {
    k++;
    t = Math.floor(t / 10);
  }

  t = number;
  let sum = 0;
  while (t > 0) {
    const d = t % 10;
    sum += intPow(d, k);
    t = Math.floor(t / 10);
  }

  return sum === number;
}

const n = 153;

if (isArmstrong(n)) {
  console.log(n + " is an Armstrong number.");
} else {
  console.log(n + " is not an Armstrong number.");
}
Try it Yourself

Explanation

Two passes over the digits: first to learn k, second to sum dk for each decimal digit d.

if (number <= 0) return false;

Guard non-positive inputs. Digit count is ambiguous for 0, and negatives are not in the usual definition used here.

while (t > 0) { k++; t = Math.floor(t / 10); }

Count digits. Integer division by ten strips one decimal digit per iteration.

sum += intPow(d, k);

Same exponent for every digit. That is what distinguishes Armstrong numbers from other digit games.

return sum === number;

Final comparison against the original value, not the working copy used while peeling digits.

2

Armstrong numbers in a range

Same isArmstrong helper as Example 1, wrapped in a loop from 1 to 200 (matches the sample output line).

JavaScript
function intPow(base, exp) {
  let r = 1;
  for (let e = 0; e < exp; e++) {
    r *= base;
  }
  return r;
}

function isArmstrong(num) {
  if (num <= 0) {
    return false;
  }
  let k = 0;
  let t = num;

  while (t > 0) {
    k++;
    t = Math.floor(t / 10);
  }

  t = num;
  let sum = 0;
  while (t > 0) {
    const d = t % 10;
    sum += intPow(d, k);
    t = Math.floor(t / 10);
  }

  return sum === num;
}

const start = 1;
const end = 200;

console.log("Armstrong numbers in the range " + start + " to " + end + ":");

let line = "";
for (let i = start; i <= end; i++) {
  if (isArmstrong(i)) {
    line += i + " ";
  }
}
console.log(line.trim());
Try it Yourself

Explanation

The outer loop is linear in the width of the interval; the inner test is logarithmic in each i.

for (let i = start; i <= end; i++)

Brute enumeration. Change start and end to whatever bounds you need.

if (isArmstrong(i)) line += i + " ";

Filter with the same predicate as the single-number script—build a string (or log each hit) instead of printf.

Optimization

Exponentiation. For fixed digit count k, precompute 0^k … 9^k in a table of length 10 and replace intPow(d,k) with a lookup when scanning many numbers.

Bounds on sums. For a given k, the maximum digit-power sum is 9^k · k. Prune candidate n values outside plausible intervals when generating large lists.

Wide integers. Promote the accumulator to BigInt (and use BigInt(n) for comparisons) if powers can exceed safe integer range.

Interview: state the O(log n) digit pass clearly; mention lookup tables only if they ask for faster range generation.

❓ FAQ

In base 10, a positive integer n is an Armstrong number (also called narcissistic) if n equals the sum of its decimal digits, each raised to the power of the total number of digits. Example: 153 has three digits and 1^3 + 5^3 + 3^3 = 153.
Yes. For a one-digit n, the digit count is 1, and n^1 = n, so every digit 1 through 9 is Armstrong. Whether to include 0 depends on the problem statement; this page treats n <= 0 as not Armstrong.
Math.pow uses floating point, which can round incorrectly for large exponents. A tiny integer multiply loop (or ** with BigInt if you switch types) keeps the equality check exact for typical interview sizes.
Definitions vary. The sample scripts return false for n <= 0 so digit counting stays well-defined and matches common contest specs that only ask for positive integers.
Let d be the number of decimal digits. Counting digits and summing digit powers are both O(d), and d is Theta(log n), so the whole test is O(log n) for a fixed base.
The sum of digit powers can exceed Number.MAX_SAFE_INTEGER before you compare to n. Use BigInt for the accumulator and digit work when the problem allows very large inputs.

🔄 Input / output examples

For the single-number script with a literal n, typical lines look like this. Swap in process.argv or a prompt if you want interactive input.

Value of nTypical line printed
153153 is an Armstrong number.
123123 is not an Armstrong number.
77 is an Armstrong number.
00 is not an Armstrong number. (with the sample guard)

For the range program with start = 1 and end = 200:

Console
Armstrong numbers in the range 1 to 200:
1 2 3 4 5 6 7 8 9 153

Edge cases and pitfalls

Most bugs come from miscounting digits, reusing a mutated copy of n, or mixing floating-point Math.pow into an integer-style test.

Input

n ≤ 0

Return false early. Otherwise 0 can slip through with a digit count of 0 in naive loops.

State

Losing the original n

Keep one variable for comparison and separate temporaries for counting and summing, or reassign from a saved copy.

Floats

Math.pow rounding

Using Math.pow then rounding can be off by one for some values. Prefer a small integer multiply loop (or BigInt powers) for exact equality tests.

Overflow

Partial sums

Digit powers add up quickly. Use BigInt or widen your numeric path when k or the digits are large enough to exceed safe integers.

⏱️ Time and space complexity

TaskTimeExtra space
Single isArmstrong(n) (two digit passes, k = O(log n))O(log n)O(1)
intPow(d, k) per digit (naive multiply loop)O(k) per callO(1)
All n in [1, U] with naive intPowroughly O(U · log² U)O(1)
Same range with a fixed table for 0..9 to the power kO(U log U) digit workO(1) table

Auxiliary memory beyond the call stack is a handful of locals in both sample scripts.

Summary

  • Definition: sum of each decimal digit raised to the digit-count power equals n.
  • Implementation: count digits, accumulate integer powers, compare to the original n; guard n ≤ 0 if required.
  • Watch-outs: avoid Math.pow rounding for strict equality, watch precision on the sum for huge n, and keep the original value for the final comparison.
Did you know?

Besides the trivial one-digit cases 19, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.

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