-2

Is there a built-in way in JavaScript to check if number is between two others? I use if(x < i && x > l), but hope there is a better solution.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109

3 Answers3

2

You won't get it done faster or better as Felix Kling said in the other post.

However, you can create a prototype method if you use it a lot:

Number.prototype.inRange = function (a, b) {
    return this >= a && this <= b;
};

var num = 8;
console.log(num.inRange(7, 8));// true
num = 4;
console.log(num.inRange(7, 8));// false
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
1

Is there a built-in way in JavaScript to check if number is between two others?

I imagine you thought about something similar to Python's l < x < h. No there is not.
x < h && x > l is the built-in way.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Not a built-in function, but nothing wrong with not being built in:

function inRange(low, num, high, inclusive) {
  inclusive = (typeof inclusive === "undefined") ? false : inclusive;
  if (inclusive && num >= low && num <= high) return true;
  if (num > low && num < high) return true;
  return false;
}

console.log(inRange(3, 7, 12));      // true
console.log(inRange(3, 7, 7, true)); // true
console.log(inRange(3, 3, 7, true)); // true

console.log(inRange(3, 7, 7));       // false
console.log(inRange(3, 3, 7));       // false
console.log(inRange(3, 9, 7));       // false
console.log(inRange(3, 9, 7, true)); // false
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127