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!