I trying to reverse user input, but I keep getting NaN. Please help.
I entered the number 123 and was expecting 321
function reverseNumber(num) {
// get user input
num = document.getElementById("num-enter").value;
// Convert the number to a string, reverse it, and convert it back to a number
const reversedString = num.toString().split("").reverse().join("");
const reversedNumber = parseInt(reversedString, 10);
// Preserve the sign of the original number
return Math.sign(num) * reversedNumber;
}
console.log(reverseNumber());
<input type="number" id="num-enter" placeholder="Enter number">
<button onclick="reverseNumber()">Add Person</button>
3
Answers
You’re calling the function immediately upon loading the page, before the user has entered a value:
The result of performing any math on an empty value is then
NaN
. At a later time you call the function again when there is a value:But then you do nothing with the result.
Remove the initial call to the function and log to the console within the function:
That way the function is only called when the button is clicked, and outputs the result to the console.
Edit: A commenter also pointed out that the
num
argument to the function can be removed, since no value is ever passed or used for it. Instead,num
is now declared within the function. I’ve also slightly cleaned up formatting.You are confusing an event listener function with a function that takes the input and produces an output.
Note: I used
String.prototype.replace
to eliminate any non-digits from the original string. I also used the spread syntax i.e.[...]
andArray.prototype.toReversed
to give the code a more modernized look.Adding the
event
param to the function is also optional. I kept it in, because it is provided when you add the function as an event listener via JS.You are almost there. There is problem with calling the function.
If you are adding a button with click event then on that event you should call the function not on page load.
Also, if you’re returning the output and trying log on console. In this case it should log on console from the function itself.
However, if you want to log on console on click event of button then there should be another function.