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

225
Vistas
Why does this works as string when it should only work as number?

So I was putting this code from an exercise on node.js in a format to front-end javascript so I could upload like a webpage. It checks if the number is prime or not. The code is:

let num = 6
let divisions = 0

for (let n = 1; n <= num; n++) { 
    if (num % n == 0) { 
        divisions++
    }
}
if (divisions == 2) {
    console.log(`O número ${num} é primo!`)
} else {
    console.log(`O número ${num} não é primo!`) 
}

This works just fine on the console.

As for the HTML5 page, I put the code inside an onclick function and just altered the variable so it gets a number from an number input box. And changed the last part to change the innerHTML of the result div instead of a console.log. And a simple alert to check if the number is higher than 2.

    function verifyPrime() {
      let num = document.getElementById('txtnum')
if (num <= 1 || num.length == 0){
    alert('insert numbers 2 or higher')

But then things went wrong. The template literals returned an [object HTMLInputElement]error. A console.log(typeof(num) returned object on the console, which I didn't get it.

Then I added a .value at the end of the getElement command. It then returned the correct number, but the typeof said it was a string.

Lastly, I added a Number() to the whole, which returned the number and the correct typeof.

My questions are:

1- Why the simple first command returned an useless object for the script?

2- Why does the script works normally when it gets a string? Shouldn't it work just with numbers since booth the loop and the second if/else asks for numbers?

I know that if it's working, it's fine... but I want to have a deeper undestanding of coding logic! Thank you!

about 4 years ago · Santiago Gelvez
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