Reverse Integer in JavaScript Problem Description:


  Given a 32-bit signed integer, reverse digits of an integer in
  JavaScript.
  
  Example 1:
  
  
  Input: 123 
  Output: 321
  
  
  Example 2:
  
  
  Input: -123 
  Output: -321
  
  
  Example 3:
  
  
  Input: 120
  Output: 21
  
  
  Note: It should return zero when it reaches out of limit [−2 ^31,  2 ^31 − 1]


My implementation

var reverse = function (x) {
  var minRange = Math.pow(-2, 31)
  var maxRange = Math.pow(2, 31) - 1

  var isNegative = false;
  if (x &lt; 0) {
    isNegative = true;
    x = (x - x - x);
  }
  var result = Number(x.toString().split('').reverse().join(''));
  (isNegative) ? result = (result - result - result) : result;
  if (result &lt; minRange || result &gt; maxRange) {
    return 0
  } else {
    return result;
  }

};


Please help to improve.
-- adding this as an answer because I can't comment.

The answer referenced in ggorlen's comment, can be improved by remarking that a (negative number % 10) is a negative number, so there is no need for sign checking.

const reverse = val =&gt; {
    let res = 0;
    const Base = 10;
    while (val) {
        res = res * Base + (val % Base);
        val = (val / Base) | 0;
    }
    return (res | 0) == res ? res : 0;
}


Tests:

reverse(1) === 1; 
reverse(-1) === -1 
reverse(0) === 0 
reverse(Math.pow(2,31) - 1) === 0 
reverse(Math.pow(-2,31)) === 0 
reverse(1463847412) === 2147483641
reverse(1463847413) === 0 


By the way, what's the reasoning behind "x = (x - x - x)"? x-x evaluates to zero. so that's just x = - x.