• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Check if the given number falls within the given range

Check if the given number falls within the given range

Check if the given number falls within the given range

Use arithmetic comparison to check if the given number is in the specified range. If the second argument, end, is not specified, the range is considered to be from 0 to start.

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;
};

// Examples
inRange(3, 2, 5); // true
inRange(3, 4); // true
inRange(2, 3, 5); // false
inRange(3, 2); // false

Source

https://www.30secondsofcode.org/js/s/in-range

Miscellaneous

Related Snippets:

  • Convert a string to an array of characters
  • How To Loop Through All The Entries In An Array Using JavaScript
  • Add an element to the DOM
  • Sorting Objects with a Primary and Secondary Property

Primary Sidebar

JSON Compare

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers