0

I've run across this function at work:

function isInt(value) {
  var x;
  if (isNaN(value)) {
    return false;
  }
  x = parseFloat(value);
  return (x | 0) === x;
}

Two questions about the above code:

  1. What is going on with the return statement? I've never used Bitwise operators in code, yet - I understand that this is the Bitwise OR operator. How does this determine whether the number passed is an integer or not?

  2. Perhaps more pertinently, is this function even necessary? I know the JavaScript Number object has an 'isInteger' method. Would it not be easier to use this?

Thanks for any responses!

Lyle
  • 41
  • 3
  • As shown by the link in James Thorpe his comment: `|` can be used to truncate the value. If the truncated value is the same as the original value, the value can be considered an integer (otherwise it contains decimals). As for 2: depends on the context, according to the browser compatibility on the mdn page, Number.IsInteger is not supported by IE – Me.Name Sep 06 '17 at 09:32
  • the `| 0` will convert a number to an integer. Kind off like Math.floor(). – Bellian Sep 06 '17 at 09:32
  • A note about 2: .isInteger() method is not supported in IE. – Dmitry Demidovsky Sep 06 '17 at 09:37
  • So, the gist of it is that bitwise operations will convert a float to an integer by truncating the value after the decimal point, since most bitwise operations only work on signed 32-bit integers. Similar to Math.floor(). Thanks. – Lyle Sep 06 '17 at 09:59

0 Answers0