Sling Academy
Home/JavaScript/[JS] Generate a random number between Min and Max and exclude a specific number

[JS] Generate a random number between Min and Max and exclude a specific number

Last updated: February 20, 2023

Creating a random number is popular stuff in Javascript that has many use cases.

This article shows you how to generate a random number between a minimum number (inclusive) and a maximum number (exclusive), and the random number you get will always be different from a given specific number.

The code:

const generateRandomBetween = (min, max, exclude) => {
    let ranNum = Math.floor(Math.random() * (max - min)) + min;

    if (ranNum === exclude) {
        ranNum = generateRandomBetween(min, max, exclude);
    }

    return ranNum;  
}    

// Test
const x = generateRandomBetween(0, 5, 3);    
console.log(x);

When you run the above code, you will get a random number of numbers 0, 1, 2, and 4. Both 5 (the maximum) but 3 will always be excluded.

Next Article: JavaScript: Convert Null, NaN, Undefined, and False to Zero

Series: JavaScript Numbers

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration