Write a Custom JavaScript function to reverse a number

How to write a javascript function that reverses a number. Before we start a program let’s understand what is javascript, Its functions and how can we reverse a number. Here, we are not using the inbuilt function.

Javascript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. It is used for creating web pages. check details JavaScript Tutorial

What is Function in Javascript?

A function in JavaScript is similar to a procedure a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Algorithm to Print Reverse Number

Input:  num

  •  Initialize rev_num = 0
  •  Iterate while num > 0

     (a) Multiply rev_num by 10 and add remainder of num  

          divide by 10 to rev_num

               rev_num = rev_num*10 + num%10;

     (b) Divide num by 10

  •  Return rev_num.

Custom JavaScript function to reverse a number

In the below code, rev_num()  is a function that will return a reverse number of the input number.

<!DOCTYPE HTML>
<html>
<title>Reverse number</title>
<script type ="text/javascript">
function rev_num()
{
var num = prompt("Enter the number to be reveresed :", " ");
var n= num;
var rev = 0, rem;
while (n>0)
{
rem = n % 10;
rev = rev * 10 + rem ;
n = Math.floor(n/10);
}
document.write("The given number is : " +num+ " <br/> The reversed number is : " +rev+ "\n");
}                 

</script>
<body style="background-color:green" onload="rev_num();">
<body>
</html>

Output

In this way, we learned how to create a Javascript function to reverse a number.