How to reverse a number that a user input [closed]

I trying to reverse user input, but I keep getting NaN. Please help.

<input type="number" id="num-enter" placeholder="Enter number">
      <button onclick="reverseNumber()">Add Person</button>
    </div>

<script>
function reverseNumber(num) {
// get user input
   num = Number( 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());
</script>

I entered the number 123 and was expecting 321

New contributor

kofa Sunday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

0

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.

0

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>

0

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật