Numbers · beginner
JavaScript Program to Check Armstrong Number
Check whether a number is an Armstrong number in JavaScript by raising each digit to the number of digits with **, and list all of them below 10,000.
- String()
- spread into an array
- reduce()
- exponent operator **
An Armstrong (narcissistic) number equals the sum of its digits, each raised to the power of the number of digits. 153 has three digits and 1³ + 5³ + 3³ = 153.
The power depends on the length: four-digit Armstrong numbers such as 9474 use the fourth power. Solutions that always cube the digits only work for three-digit numbers.
The program
function isArmstrong(n) {
const digits = [...String(n)].map(Number);
const power = digits.length;
return digits.reduce((sum, d) => sum + d ** power, 0) === n;
}
for (const n of [153, 370, 9474, 123]) {
console.log(n, isArmstrong(n) ? "is an Armstrong number" : "is not an Armstrong number");
}
const found = [];
for (let n = 1; n < 10000; n++) if (isArmstrong(n)) found.push(n);
console.log(found.join(", "));153 is an Armstrong number
370 is an Armstrong number
9474 is an Armstrong number
123 is not an Armstrong number
1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474How it works
- String(n) turns 153 into "153", and the spread [...] splits it into ["1", "5", "3"].
- map(Number) converts each character back into a number.
- digits.length is the power, and reduce() adds up each digit raised to it with **.
- The number is an Armstrong number when the sum equals the original. Every single-digit number qualifies.
Watch it run line by line
In the isArmstrong(153) frame, digits is [1, 5, 3] and power is 3. The reduce callback runs once per digit, and its return values grow 1, 126, 153.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Using arithmetic instead of strings
n % 10 is the last digit and Math.trunc(n / 10) removes it. This works without converting to a string.
const n = 9474;
const power = String(n).length;
let total = 0;
for (let rest = n; rest > 0; rest = Math.trunc(rest / 10)) {
total += (rest % 10) ** power;
}
console.log(total === n);trueCommon mistakes
- Always cubing (d ** 3), which rejects 9474.
- Dividing with / and no Math.trunc(): rest / 10 is a decimal, so the loop runs many extra times and the sum is wrong.
- Comparing the sum with the modified number instead of the original.
Try it yourself
- Find the three five-digit Armstrong numbers.
- Read a number with prompt() and report whether it is an Armstrong number.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.