Random

JavaScript Randomization examples


Random number in a range

Generate a random number in a range. Source

  • Example:

    function getRandumNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

Random number with fixed length

Generate a random number with fixed length. Source

  • Example:

    function getRandumNumber(length) {
        const min = Math.pow(10, (length-1));
        const max = Math.pow(10, (length));
        return Math.floor(Math.random() * (max - min) + min);
    }

Random string

Generate a random string. Source

  • Example:

    function getRandomString(length) {
      const allowedCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      const allowedCharacterLength = allowedCharacters.length;
    
      let result = '';
    
      for ( let i = 0; i < length; i++ ) {
        result += allowedCharacters.charAt(Math.floor(Math.random() *  allowedCharacterLength));
      }
    
      return result;
    }

Random UUID

Generate a random UUID. Source

  • Example:

    function getUUID() {
      return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
          (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
      );
    }

Random color

Generate a random color. Source

  • Example:

      function getRandomColor() {
          const availableCharacters = '0123456789ABCDEF';
          const availableCharacterLength = availableCharacters.length;
    
          let color = '#';
      
          for (let i = 0; i < 6; i++) {
            color += availableCharacters[Math.floor(Math.random() * availableCharacterLength)];
          }
      
          return color;
      }

Random date

Generate a random date. Source

  • Example:

      function getRandomDate() {
          const maxDate = Date.now();
          const timestamp = Math.floor(Math.random() * maxDate);
          return new Date(timestamp);
      }

Random date in a range

Generate a random date in a range. Source

  • Example:

      function getRandomDate(startDate, endDate) {
          const minValue = startDate.getTime();
          const maxValue = endDate.getTime();
          const timestamp = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue);
          return new Date(timestamp);
      }

Last updated