How to reverse a number in JavaScript

Examples using an arrow function and regular JS function

artismarti
We’ve moved to freeCodeCamp.org/news
2 min readFeb 3, 2019

--

Photo by chuttersnap on Unsplash

Reversing a string or reversing a number is one of the common questions asked at programming interviews. Let’s take a look at how this is done.

Rules/Limitations:

  • Negative numbers should remain negative.

ex. -12345becomes -54321

  • Any leading zeroes should be removed.

ex. 321000 becomes 123 & not 000123

  • The function can accept floats or integers.

ex. 543.2100 becomes 12.345

  • The function will return integers as integers.

ex. 54321 becomes 12345 & not 12345.00

Solving with an Arrow Function:

Solving with a Regular Function:

Difference between an Arrow function & Regular function:

In this example, the only difference between the Arrow Function and the Regular function is that the Regular function needs to provide an explicit return value.

Arrow functions have an implicit return value — if they can be written in one line, without the need for the{} braces.

View this on repl.it

Let’s break the steps down:

  • Convert the number to a string

num.toString() converts the given number into a String. We do this so we can use the split function on it next.

  • Split the String into an Array

num.split('') converts the String into an Array of characters. We do this so we can use the Array reverse function (which does not work on a String).

  • Reverse the Array

num.reverse() reverses the order of the items in the array.

  • Join it back into a string

num.join('') reassembles the reversed characters into a String.

  • Parse the input value into a floating point number:

parseFloat(num) converts num into a float from a String.

Note: parseFloat runs in the end (even though it is on the first line of the function) on the reversed number and removes any leading zeroes.

  • Multiply it by the sign of the original number — to maintain the negative value.

num * Math.sign(num) multiplies the number with the sign of the original number provided.

And, there you have it!

--

--

artismarti
We’ve moved to freeCodeCamp.org/news

Software Developer, Product Manager, biryani loving, फ़ेमिनिस्ट किल जॉय. Jill of all trades. Mistress of some.