Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda