Table of Contents
Example 1
In order to square every digit of a number in JavaScript, we can use the following function:
function givenNum(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
givenNum(5667);
// outputs 25363649
Explanation and break-down
In order to know what is happening within this function we have to break it down. So, in the first step we split the digits of the number to a string of individual numbers:
function givenNum(num) {
return ('' + num).split('');
}
givenNum(5667);
// outputs ['5','6','6','7']
Now look at the next step carefully and try to understand. We’ve used the .map() method wherein we’ve used a function as an argument which squares each digit in the number:
function givenNum(num) {
return ('' + num).split('').map(function (val) { return val * val;});
}
givenNum(5667);
// outputs [25, 36, 36, 49]
In the last step we used join() and encapsulated the whole code with a Number() function so that the final output shows up as a number(25363649) and not as a string(‘25363649’).
Example 2
Now, let’s do the same task thing using a slightly different code:
function squareDigitsOfNum(num){
return +String(num).split('').map((i) => i*i).join('');
}
squareDigitsOfNum(776);
// outputs 494936
Example 3
Another way to square the digits of a number is this:
function squareTheDigits(num){
var string = num.toString();
var results = [];
for (var i = 0; i < string.length; i++){
results[i] = string[i] * string[i];
}
return Number(results.join(''));
};
console.log(squareTheDigits(2234));
// outputs 44916