Skip to main content

JavaScript function to check if the given number falls within a given range.

/**
 * Checks if the given number falls within the given range.
 *
 * https://www.30secondsofcode.org/snippet/inRange
 *
 * @param {Number} n The number to check if it is in a specified range.
 * @param {Number} start The start range.
 * @param {Number} [end] The end range. If end range is not specified, the range is considered to be from `0` to `start`
 * @return {Boolean} Returns true if the given number falls within the given range, otherwise false.
 */
const inRange = (n, start, end = null) => {
    if (end && start > end) [end, start] = [start, end];
    return end == null ? n >= 0 && n < start : n >= start && n < end;
};

//
// Example

console.log(inRange(3, 2, 5)); // true
console.log(inRange(3, 4)); // true
console.log(inRange(2, 3, 5)); // false
console.log(inRange(3, 2)); // false