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

Example

The code for this will be −

 Live Demo

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));

Output

And the output in the console will be −

1491681

Updated on: 26-Feb-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements