for (let i = 1; i<= num; i++){
contador++;
if((contador*contador) === num){
break;
}
}
return contador;
}
//this is the easy way and is perfectly functional in the console and event onchange.
function squaredRoot2(num = null) {
return Math.sqrt(num);
}
//in the console the function squareRoot is functional, but in the event onchange does not work, why?
input.onchange = function() {
let num = input.value;
if (isNaN(num)) {
para.textContent = 'You need to enter a number!';
} else {
para.textContent = num + ' squared is ' + squared(num) + '. ' +
num + ' cubed is ' + cubed(num) + '. ' +
num + ' square root is ' + squaredRoot(num) + '. ' +
num + ' factorial is ' + factorial(num) + '.';
}
}
At a first glance I only see a problem when using a number which doesn’t have a integer root (like 24). Since the multiplication in your function could never reach it.
To make it easier could you please put your code in an online editor like https://codepen.io and tell us what exactly doesn’t work as expected.
Hi @mikoMK Thank you for such a nice words, this is the codepen link https://codepen.io/falling-skx/pen/xxrOoWN . When i put in the input the number 4 for example, it does not work like i expect, if you have an idea please let me know.
Thanks for the Pen, @Matias_Concha
Now I see the problem. Everything from an input field is a string. It doesn’t matter with the other functions since they automatically convert the string into an integer. In your function you are using the strict equality operator (===) which also checks the type. Since it is comparing an integer to a string it is always false and the loop never breaks.
You have several possibilities to solve this problem:
Wow!!!, i broke my head with this exercise and the solution is very simple, i have a lot to learn, thanks you very much for your time and your explanation.