Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda