Squaring every digit of a number using split() in JavaScript

We are required to write a JavaScript function that takes in a number as the first and the only argument. The function should then square every digit of the number, append them and yield the new number.

For example −

If the input number is −

const num = 12349;

Then the output should be −

const output = 1491681;

because '1' + '4' + '9' + '16' + '81' = 1491681

How It Works

The solution uses split('') to convert each digit into an array element, then squares each digit and concatenates the results:

  1. Convert the number to a string using String(num)
  2. Split the string into individual digits using split('')
  3. Square each digit and concatenate to build the result
  4. Convert the final string back to a number

Example

The code for this will be −

const num = 12349;
const squareEvery = (num = 1) => {
    let res = '';
    const numStr = String(num);
    const numArr = numStr.split('');
    numArr.forEach(digit => {
        const square = (+digit) * (+digit);
        res += square;
    });
    return +res;
};
console.log(squareEvery(num));
1491681

Alternative Approach Using map()

You can achieve the same result using map() and join():

const squareEveryMap = (num) => {
    return +String(num)
        .split('')
        .map(digit => digit * digit)
        .join('');
};

console.log(squareEveryMap(12349));
console.log(squareEveryMap(567));
1491681
254649

Step-by-Step Breakdown

Let's trace through the process with number 123:

const num = 123;
console.log("Original number:", num);

const numStr = String(num);
console.log("As string:", numStr);

const digits = numStr.split('');
console.log("Split digits:", digits);

const squares = digits.map(digit => digit * digit);
console.log("Squared digits:", squares);

const result = squares.join('');
console.log("Joined result:", result);
console.log("Final number:", +result);
Original number: 123
As string: 123
Split digits: [ '1', '2', '3' ]
Squared digits: [ 1, 4, 9 ]
Joined result: 149
Final number: 149

Conclusion

The split('') method effectively converts each digit into an array element, making it easy to process and square individual digits. This approach works well for transforming numbers digit by digit in JavaScript.

Updated on: 2026-03-15T23:19:00+05:30

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements