skip to Main Content

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


  1. You’re calling the function immediately upon loading the page, before the user has entered a value:

    console.log(reverseNumber());
    

    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:

    onclick="reverseNumber()"
    

    But then you do nothing with the result.

    Remove the initial call to the function and log to the console within the function:

    <script>
    function reverseNumber() {
      // get user input
      let 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
      console.log(Math.sign(num) * reversedNumber); // <--- log to console here
    }
    // <--- do not call the function here
    </script>
    

    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.

    Login or Signup to reply.
  2. You are confusing an event listener function with a function that takes the input and produces an output.

    // A "pure" function that takes a number or string
    // and returns a reversed number
    const reverseNumber = (n) => {
      const str = typeof n !== 'string' ? n.toString() : n;
      const digits = [...str.replace(/[^d]/g, '')].toReversed();
      return Math.sign(n) * parseInt(digits.join(''), 10);
    };
    
    // Global event handler function
    function onReverse(event) {
      const inputEl = document.querySelector('#num-enter');
      inputEl.value = reverseNumber(inputEl.value); // Re-assign value
    }
    
    // Alternatively, attach the event via JS
    //document.addEventListener('click', onReverse);
    <input type="number" id="num-enter" placeholder="Enter number" value="-12345">
    <button onclick="onReverse(event)">Add Person</button>

    Note: I used String.prototype.replace to eliminate any non-digits from the original string. I also used the spread syntax i.e. [...] and Array.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.

    Login or Signup to reply.
  3. 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.

    function reverseNumber() {
      console.log(getNumberReversed());
    }
    
    function getNumberReversed() {
      // 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);
      // Preserve the sign of the original number
      return reversedNumber;
    }
    <input type="number" id="num-enter" placeholder="Enter number">
    <button onclick="reverseNumber()">Add Person</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search