Emmanuel Akinfulubi

JavaScriptFunction

Function to reverse a number in JavaScript

Beginner · 4 min read

Reversing a number means writing its digits backwards: 32243 becomes 34223. It turns up in number puzzles, in checks for palindrome numbers like 12321, and in interview questions about loops and strings.

In this tutorial you will write a function called reverseNumber. You give it a number and it gives back a number with the digits reversed. Along the way you will decide what should happen to a minus sign and to zeros at the end, two cases most quick answers get wrong. You need to know what a function is and what a string is.

Numbers have no reverse button

A number in JavaScript is a value you do maths with. It has no idea of "digits" or "first" and "last". Text does. So the easiest plan is to borrow text for a moment:

  1. Turn the number into a string, like '32243'.
  2. Reverse the characters.
  3. Turn the result back into a number.

Two built-in functions do the converting. String(n) turns a number into text, and Number(text) turns text back into a number:

JavaScript

console.log(String(32243));   // '32243'
console.log(Number('34223')); // 34223

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

1 Reverse a number

easy

32243 should give 34223. Decide what happens to a negative number and to trailing zeros.

Stuck? Three hints, smallest first
  1. 1. Convert to a string, reverse the characters, convert back.
  2. 2. Number(‘00123’) is 123, so reversing 32100 loses the zeros.
  3. 3. Keep the sign aside and reverse only the digits.

Step 1: reverse the digits as text

To reverse text, spread it into an array of characters with [...text], flip the array with reverse(), then glue it back together with join(''):

Step 1

const digits = [...String(32243)].reverse().join('');
console.log(digits);         // '34223'
console.log(Number(digits)); // 34223

That already works for the example. Now try a negative number.

Step 2: the minus sign gets in the way

JavaScript

const backwards = [...String(-456)].reverse().join('');
console.log(backwards);         // '654-'
console.log(Number(backwards)); // NaN

The minus sign is a character too, so it moved to the end. '654-' is not a valid number, and Number gives NaN, which means "not a number". That is the wrong turn this step is here to show.

Step 3: keep the sign aside

The fix is to take the sign off first, reverse only the digits, then put the sign back. Two helpers do this:

  • Math.abs(n) gives the number without its sign, so -456 becomes 456.
  • Math.sign(n) gives -1 for a negative number, 1 for a positive one and 0 for zero.

Step 3

console.log(Math.abs(-456));  // 456
console.log(Math.sign(-456)); // -1
console.log(Math.sign(32243)); // 1

Multiplying by the sign at the end restores it: -1 * 654 is -654. For zero, 0 * 0 is still 0.

Step 4: put it in a function

Step 4

function reverseNumber(n) {
  const sign = Math.sign(n);
  const digits = [...String(Math.abs(n))].reverse().join('');
  return sign * Number(digits);
}
console.log(reverseNumber(32243)); // 34223
console.log(reverseNumber(-456));  // -654
console.log(reverseNumber(0));     // 0

sign * Number(digits) also makes sure the function returns a real number, not a string.

Step 5: zeros at the end disappear

Try a number that ends in zeros:

JavaScript

console.log(reverseNumber(32100)); // 123
console.log(Number('00123'));      // 123

The reversed text is '00123'. A number can't store zeros at the front, so Number('00123') is just 123. This is not a bug you can fix inside a number. If those zeros matter to you, you are really reversing text, and the function should return a string instead.

It also means reversing twice doesn't always bring you back: 32100 becomes 123, and 123 becomes 321.

Step 6: refuse things that aren't numbers

Infinity and NaN are both of type number in JavaScript, but they have no digits to reverse. Number.isFinite(n) is true only for an ordinary number, so the answer starts with a guard line:

Step 6

console.log(Number.isFinite(32243));    // true
console.log(Number.isFinite(Infinity)); // false

In the full answer, the first line of reverseNumber is if (!Number.isFinite(n)) return NaN;, so anything that isn't a normal number gives NaN straight away.

The full solution

The panel has reverseNumber with its guard, plus a second version, reverseByMath, that does the same job with arithmetic only: left % 10 takes the last digit off, and out * 10 + digit adds it to the other end. It prints the results for several numbers, including 32100. Press Run to see them.

The answer

function reverseNumber(n) {
  if (!Number.isFinite(n)) return NaN;
  const sign = Math.sign(n);                       // keep the sign out of it
  const digits = [...String(Math.abs(n))].reverse().join('');
  return sign * Number(digits);
}

// Arithmetic, no strings. Same answer, and it shows what is really happening.
function reverseByMath(n) {
  const sign = Math.sign(n);
  let left = Math.abs(n);
  let out = 0;
  while (left > 0) {
    out = out * 10 + (left % 10);
    left = Math.floor(left / 10);
  }
  return sign * out;
}

for (const n of [32243, 1, 0, -456, 32100, 120, 1000]) {
  console.log(String(n).padEnd(8), '->', reverseNumber(n));
}
console.log('--- trailing zeros cannot survive ---');
console.log("reverse 32100 gives 121 as digits '00123', and Number('00123') is", Number('00123'));
console.log('so the leading zeros are dropped, which is arithmetic, not a bug');

Output


      
12 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 12 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

12 checks

test("the example in the question", reverseNumber(32243), 34223);
test('a single digit is itself', reverseNumber(1), 1);
test('zero is zero', reverseNumber(0), 0);
test('a negative number keeps its sign', reverseNumber(-456), -654);
test('trailing zeros disappear', reverseNumber(32100), 123);
test('because a number cannot hold leading zeros', Number('00123'), 123);
test('a round number becomes a single digit', reverseNumber(1000), 1);
test('the arithmetic version agrees everywhere', [32243, 1, 0, -456, 32100, 120, 1000].every((n) => reverseNumber(n) === reverseByMath(n)), true);
test('reversing twice gets back to the start, when there are no trailing zeros', reverseNumber(reverseNumber(32243)), 32243);
test('but not when there were', reverseNumber(reverseNumber(32100)) === 32100, false);
test('the result is a number, not a string', typeof reverseNumber(32243), 'number');
test('a non-finite input gives NaN', Number.isNaN(reverseNumber(Infinity)), true);

The interesting part is what the type forces. A number cannot store a leading zero, so 32100 reverses to 123 and there is no way around it — the assertion checks Number('00123') to make the reason visible. If those zeros matter, you are reversing a string, not a number, and should return one.

Handling the sign separately is what stops -456 becoming the string '654-'. The arithmetic version is worth reading once: out * 10 + (left % 10) peels a digit off one end and pushes it onto the other, which is the same idea without going through text.

Common mistakes

  • Reversing the minus sign with the digits. '-456' reversed is '654-', which becomes NaN. Take the sign off with Math.abs and put it back with Math.sign.
  • Returning the string. '34223' looks right on screen, but '34223' + 1 is '342231'. Convert back with Number.
  • Expecting zeros to survive. 32100 can only reverse to 123 as a number. Return a string if the zeros matter.

Try it yourself

  1. Write isPalindromeNumber(n) that returns true when reverseNumber(n) === n. Test it with 12321 and 123.
  2. Write reverseDigitsText(n) that returns a string and keeps the zeros, so 32100 gives '00123'.
  3. Follow reverseByMath(123) on paper, writing down left and out after each turn of the loop.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.