Square every digit of a number - JavaScript

We are required to write a JavaScript function that takes in a number and returns a new number in which all the digits of the original number are squared and concatenated.

For example: If the number is ?

9119

Then the output should be ?

811181

because 9² is 81 and 1² is 1.

Example

Following is the code ?

const num = 9119;
const squared = num => {
    const numStr = String(num);
    let res = '';
    for(let i = 0; i < numStr.length; i++){
        const square = Math.pow(+numStr[i], 2);
        res += square;
    };
    return res;
};
console.log(squared(num));
811181

Alternative Approach Using Array Methods

We can also solve this using array methods with a more functional approach:

const squareDigits = num => {
    return String(num)
        .split('')
        .map(digit => Math.pow(+digit, 2))
        .join('');
};

console.log(squareDigits(9119));
console.log(squareDigits(765));
console.log(squareDigits(0));
811181
493625
0

How It Works

The algorithm follows these steps:

  1. Convert the number to a string to access individual digits
  2. Iterate through each character (digit)
  3. Convert each digit back to number and square it using Math.pow()
  4. Concatenate all squared results into a final string

Comparison

Method Code Length Readability Performance
For Loop Longer Good Faster
Array Methods Shorter Better Slightly slower

Conclusion

Both approaches effectively square each digit and concatenate the results. The array method approach is more concise and functional, while the for loop provides better performance for large numbers.

Updated on: 2026-03-15T23:18:59+05:30

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements