An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits, each raised to the power of the total number of digits. For example, 153 has 3 digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 — so 153 is an Armstrong number.
Let’s write a JavaScript program that checks whether a given number is an Armstrong number, using a basic for loop to extract and sum the digit powers.
JavaScript Program to Check Armstrong Number (Using a Loop)
function isArmstrong(num) {
const numStr = String(num);
const power = numStr.length;
let sum = 0;
// add each digit raised to the power of total digit count
for (let i = 0; i < numStr.length; i++) {
const digit = Number(numStr[i]);
sum += Math.pow(digit, power);
}
return sum === num;
}
const number = 153;
if (isArmstrong(number)) {
console.log(`${number} is an Armstrong number`);
} else {
console.log(`${number} is not an Armstrong number`);
}
Output:
153 is an Armstrong number
JavaScript Program to Check Armstrong Number (Using reduce())
The same logic can be written more compactly with Array.prototype.reduce() once the number is split into an array of digits.
function isArmstrongReduce(num) {
const digits = String(num).split("");
const power = digits.length;
const sum = digits.reduce((acc, digit) => acc + Math.pow(Number(digit), power), 0);
return sum === num;
}
console.log(isArmstrongReduce(9474)); // 4 digits: 9^4 + 4^4 + 7^4 + 4^4 = 9474
console.log(isArmstrongReduce(123));
Output:
true
false
Both versions run in O(d) time, where d is the number of digits — effectively constant time for any normal-sized number. The loop version is easier to read for beginners; the reduce() version is the idiomatic one-liner you’ll see more often in real codebases.
