0

There is the possibility of integer overflow when you try to compare numbers using subtraction in Java. See Q: Java Integer compareTo() - why use comparison vs. subtraction?

But, unlike Java, JavaScript handles overflows and underflows.

The question is Does the following implementation of compareNumeric() work correctly in JavaScript?

// compareNumeric() one-liner
function compareNumeric(a, b) {
    return a - b;
}

EDIT. The compareNumeric function should return

  • negative value when a < b;
  • 0 when a = b;
  • positive value when a > b.

a and b are Numbers.

Community
  • 1
  • 1
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259

1 Answers1

1

Does the following implementation of compareNumeric() work as expected in JavaScript?

Yes. As you've already figured out, there are no integer overflows or underflows in javascript (because all the number values are floats). If your values are getting too large or too small, you'll end up with Infinity or -Infinity, which are positive and negative respectively.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375