Home > Back-end >  Square every digit in JavaScript - string * string become a number?
Square every digit in JavaScript - string * string become a number?

Time:03-06

I am very new to JavaScript and still learning the fundamentals. I was completing a JavaScript challenge were i needed to square every number eg. 881 become 64641. My code is below which i am happy with but I have managed to get myself confused by overthinking.

When i do numArray[i] * numArray[i] as they are both strings does JavaScript automatically convert to a number in order for the numbers to square themselves. Did it turn it into a number - square the number - then turn back into a string again. Which is why i have to do Number(squareArray.join(''));

The reason i ask is I know that if you do string * number it turns to a number, i would if something similar happens. If I am wrong please can someone explain so I can understand.

let numArray = num.toString();   //turn number to a string
let squareArray = [];   // create an array to save the new values of the string
for (let i = 0; i < numArray.length; i  ) {   // iterate through the string
 squareArray[i] = numArray[i] * numArray[i];   // save the square of the number to the array 
  }
return Number(squareArray.join(''));   // turn the array into a string and then into a number}

CodePudding user response:

Few observations :

  • As you want to make a square of a number, why converting those into a string ? Keep it in number form.
  • As you want each square number element should concat beside each other. You can achieve that only by joining via Array.join('').

Suggestion : Use Array.map() to get square of each number.

Working Demo :

let numArray = [1,2,3,4,5];

const squareArray = numArray.map(item => item * item);

console.log(Number(squareArray.join('')));

  • Related