Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
Square every digit in JavaScript - string * string become a number?

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}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!