Best Website-BuildersBest Website-Builders
    What's Hot

    Jennifer Lawrence is reinventing herself for a comeback

    March 9, 2023

    Reddit – Dive into anything

    March 9, 2023

    T-level delays: Colleges face disruption after courses are pushed back

    March 9, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Apple Releases Safari Technology Preview 165 – Brings Bug Fixes and Performance Improvements

      March 9, 2023

      15 Best Courses to Become Full Stack Developer in 2023

      March 9, 2023

      Junior DevOps Engineer at Datafin Recruitment

      March 9, 2023

      Cricket betting tips and fantasy cricket match predictions: Sharjah Hundred League 2023

      March 9, 2023

      Charlotte Sleep Solutions Opens in University City | News

      March 9, 2023
    • Joomla

      Web Content Management Systems Market Business Growth Potential 2023-2030

      March 6, 2023

      How to create a successful content strategy framework

      March 3, 2023

      Free Website Hosting Services for Efficient and Reliable Work

      March 2, 2023

      Bluehost Review 2023 – Is It the Fastest Hosting Service?

      March 2, 2023

      Intermediate PHP Developer – IT-Online

      March 1, 2023
    • PHP

      Jennifer Lawrence is reinventing herself for a comeback

      March 9, 2023

      March 9, 2023 — Biggest news story of the day

      March 9, 2023

      Likely to get worse, according to asthma experts

      March 8, 2023

      ‘Who Killed Robert Wone?’ by Peacock

      March 8, 2023

      Former fitness influencer Brittany Dawn’s trial postponed

      March 8, 2023
    • UX

      Top Design Agencies in March, According to DesignRush

      March 9, 2023

      Spotify announces new tools and features to improve user experience

      March 9, 2023

      Think Silicon to Showcase Latest Ultra-Low-Power Graphics and AI Solutions for Edge Computing at Embedded World 2023

      March 9, 2023

      Think Silicon to Showcase Latest Ultra-Low-Power Graphics and AI Solutions for Edge Computing at Embedded World 2023

      March 9, 2023

      PS5 System Update 7.0 Rolling Out Worldwide

      March 9, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Bing now has 100 million users powered by ChatGPT, but will it continue?

      March 9, 2023

      This is the gaming laptop deal you need to buy now if you care about portability.

      March 9, 2023

      Microsoft 365 is launching Accessibility Assistant

      March 9, 2023

      Microsoft slowly but surely admits that Windows 11’s taskbar was wrong.

      March 9, 2023

      Oppo Introduces Its Latest Foldable Oppo Find N2 Flip – And It’s A Fantastic Flip

      March 9, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » Generate random numbers using Math.random() in JavaScript
    JavaScript

    Generate random numbers using Math.random() in JavaScript

    websitebuildersnowBy websitebuildersnowSeptember 20, 2022No Comments10 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In this article, we’ll look at how to generate random numbers in JavaScript. Math.random()load random images, select random elements from arrays, generate random colors, characters, strings, phrases, and passwords, and build reusable functions for a wide range of purposes.

    Randomness in JavaScript

    It’s always nice to be able to add an element of randomness to your program. You may want to spice up your website by adding random styles, generating random phrases, or adding an element of chance to your game (for example, in this Numble game these are widely used).

    Unfortunately, creating truly random values ​​is actually very difficult (unless you have access to radioactive material or use a monkey with a keyboard). To avoid this, programming languages ​​generate using deterministic methods. pseudorandom number.these are numbers appear Random, but actually generated by a function that accepts seed value Based on events such as mouse pointer time and position.

    in JavaScript random Functions that are built-in methods Math object. The ECMAScript standard does not specify how this function generates random numbers, so implementation is left to browser vendors. At the time of this writing, all major browsers use his xorshift128+ algorithm in the background to generate pseudo-random numbers.

    To use, simply enter Math.random() and returns a pseudorandom floating point decimal number between 0 (inclusive) and 1 (exclusive).

    const x = Math.random();
    

    This can be expressed as the following inequality:

    0 <= x < 1
    

    But what if you want a random number greater than 1? Easy: Just multiply and zoom in. For example, multiplying the result by 10 produces a value between 0 (inclusive) and 10 (exclusive).

    const y = Math.random()*10
    

    The reason for this can be seen by multiplying both sides of the previous inequality by 10.

    0 <= y < 10
    

    However, the result is still a floating point decimal number. What if we want a random integer? Simple: all we need to do is Math.floor Use a function to round the return value to an integer below. The following code assigns a random integer between 0 and 9 to a variable. z:

    const z = Math.floor(Math.random()*10)
    

    Note that multiplying by 10 only returns values ​​up to 9.

    You can generalize this method to create a function that returns a random integer between 0 and up to 0. but does not includea number provided as an argument:

    function randomInt(number){
      return Math.floor(Math.random()*(number))
    }  
    

    You can use this function to return a random number between 0 and 9.

    const randomDigit= randomInt(10)
    

    Now you have a way to create random integers. But what about random integers between two different values ​​that don’t necessarily start at zero? Using the code above, addition Value to start the range with. For example, if you want to generate a random integer between 6 and 10, use the code above to generate a random integer between 0 and 4 and add 6 to the result.

    const betweenSixAnd10 = Math.floor(Math.random()*5) + 6
    

    to generate a random integer between 0 When 4actually had to hang 5.

    You can generalize this method to create a function that returns a random integer between two values.

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

    This is a simple generalization of the code I wrote to get a random number between 6 and 10, but with 6 as min parameter and 10 is max parameters. To use it, simply enter two arguments representing the upper and lower bounds of the random number (inclusive). So to simulate rolling a hexahedral die, you can use the following code to return an integer between 1 and 6.

    const dice = randomIntBetween(1,6)
    

    How randomIntBetween the function works. In the demo below I am connecting to some HTML so you can change the values. min When max Click the button to generate a random integer (this can be used to replicate the various size dice used in Dungeons & Dragons and similar games).

    look at the pen
    Random Integer – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    There are some functions for generating random integers, so you can do interesting things with them.

    Load random image

    first, randomInt Ability to load random photos from the Lorem Picsum website. This site provides a database of placeholder images, each with a unique integer ID. This means that you can create links to random images by inserting random integers into the URL.

    Simply set the following HTML to display an image with an ID of 0.

    <button id="randomPhoto">Random Photo</button>
    <p id="photo"><img src="https://picsum.photos/id/0/200/200"></p>
    

    Then hook the following JavaScript to generate a random integer for the ID and update the HTML to randomly display a new image when the button is clicked.

    document.getElementById("randomPhoto").addEventListener("click",e => document.getElementById("photo").innerHTML = `<img src="https://picsum.photos/id/${randomInt(100)}/200/200">`)
    

    You can see this in the CodePen demo below.

    look at the pen
    Random Photo – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random colors

    In HTML and CSS, colors are represented by three integers from 0 to 255, written in hexadecimal (base 16). The first represents red, the second represents green, and the third represents blue.This means that we can use randomInt Use a function to generate three random numbers between 0 and 255 and convert them to base 16 to create random colors.To convert a number to another base, replace the argument with toString method, the following code returns a random hexadecimal number between 0 and FF (255 hex).

    randomInt(0,255).toString(16)
    << 2B
    

    with this, randomColor Functions that return HTML color codes:

    function randomColor(){ 
      return `#${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}`
    }
    

    This returns a template literal that starts with a hash character that starts with every HTML color code, and concatenates three random integers between 0 and 255 in hexadecimal at the end.

    call randomColor The function returns a random HTML color string.

    randomColor()
    << #c2d699
    

    In the CodePen demo below, I’ve connected a function to an HTML button so that the background color of the document changes whenever the button is clicked.

    look at the pen
    Random Color – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Random letter generation

    We already have functions to create random integers, but what about random characters? Fortunately, there’s a nice way to convert integers to characters using a base. In base 36, the integers 10 through 35 are represented by the letters ‘a’ through ‘z’. This can be verified by converting some values ​​to base 36 in the console. toString Method:

    (24).toString(36)
    (16).toString(36)
    

    Knowing this, it’s easy to write: randomLetter functions that use us randomInt A function that generates a random integer between 10 and 35 and returns its base 36 string representation:

    function randomLetter(){
     return randomInt(10,35).toString(36)
    }
    

    talking randomLetter I need to return a random lowercase letter from ‘a’ to ‘z’.

    randomLetter()
    << "o"
    
    randomLetter()
    << "g"
    

    I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

    look at the pen
    Random Letters – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random string

    Now that we can create random characters, we can combine them to create random strings.let’s write randomString a function that accepts a single parameter, n — This represents the number of random characters you want in the returned string.You can create random strings by creating an array or length n and, map A method that changes each element to a random character. next, join A method to convert an array to a random string:

    function randomString(numberOfLetters){
      return [...Array(numberOfLetters)].map(randomLetter).join``
    }
    

    talking randomString(n) should return a random string of n letter:

    randomString(5)
    << "xkibb"
    
    randomLetter(3)
    << "bxd"
    

    I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

    look at the pen
    Random String – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    select a random element from an array

    It is often useful to be able to select random elements from an array.This can be done fairly easily using our randomInt function. You can randomly choose an index in an array by using the length of the array as an argument and returning the element at that index from the array.

    function randomPick(array){
     return array[randomInt(array.length)]
    }
    

    For example, with the following array representing a list of fruits:

    const fruits = ["🍏",🍌","🍓","🥝","🍋","🍐","🫐","🍉"]
    

    You can use the following code to pick a fruit randomly.

    randomPick(fruits)
    << "🍉"
    

    generate random phrases

    Now that we have a function that selects a random element from the array, we can use it to create a random phrase. This technique is often used as placeholder usernames on websites. First, create three arrays as shown below. One contains adjective strings, one contains colors, and other nouns.

    const adjectives = ["Quick","Fierce","Ugly","Amazing","Super","Spectacular","Dirty","Funky","Scary"]
    const colors = ["Brown","Red","Orange","Black","White","Purple","Pink","Yellow","Green","Blue"]
    const nouns = ["Fox","Bear","Monkey","Hammer","Table","Door","Apple","Banana","Chair","Chicken"]
    

    Now that we have these three sequences, it’s easy to create random phrases. randomPick function. Select random elements from each array, concatenate them, and put a space between them to create a clause.

    function randomPhrase(a,c,n){
      return `${randomPick(a)} ${randomPick(c)} ${randomPick(n)}`
    }
    

    talking randomPhrase It should return a slightly funny-sounding random phrase containing colors, adjectives, and nouns.

    randomPhrase()
    << "Funky Pink Chicken"
    

    I’ve hooked this function up to an HTML button, so you can create some wacky phrases by pressing the button in the CodePen demo below.

    look at the pen
    Random Phrase – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random password

    The final use of random integers we’ll look at is generating random password strings. A general rule for passwords is that they contain at least:

    • 8 characters
    • one number
    • 1 non-alphanumeric special character

    Examples that fit these rules are:

    secret!1
    

    We already have a function that can generate each of these elements.First, use randomString(6) Create a random string of 6 characters. next, randomPick Use a function to select special characters from an array, then use randomInt(9) Returns a random number. Now just concatenate them together and you have a randomly generated password!

    You can boil this down to a function that returns a random password string.

    function generatePassword(){
      return randomString(6) + randomPick(["!","%","?","&","@","£","$","#"]) + randomInt(9)
    }
    

    talking generatePassword It should return a random password that passes the above three rules.

    generatePassword()
    << "ykkefn@8"
    

    Now that you’ve connected this function to an HTML button, try pressing the button to generate a random password in the CodePen demo below.

    look at the pen
    Random Password – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    One thing to note is how all the functions we’ve written so far are randomInt the first function I wrote.of generatePassword For example, the function we just wrote is randomInt,randomPick When randomString function…and randomString the function is randomLetter function! This is the foundation of programming, using functions as building blocks for more complex functions.

    summary

    We’ve seen how to generate random numbers in JavaScript. I hope you find this guide helpful.of randomInt The function is certainly a nice function to have in your locker and can help add some randomness to your project.

    You can see all the examples covered in this article in the following CodePen demos.

    look at the pen
    Randomness – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Related reading:



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleHelp creating CSS tables with ROWSPAN – HTML & CSS – SitePoint Forums
    Next Article The Daily Herald – K1 Britannia Foundation launches support program for troubled youth
    websitebuildersnow
    • Website

    Related Posts

    DAP — Web3’s New App Success Metrics | Eric Elliot | | The JavaScript Scene | March 2023

    March 9, 2023

    Top 10 AI Extensions for Visual Studio Code — Visual Studio Magazine

    March 8, 2023

    Top 10 AI Extensions for Visual Studio Code — Visual Studio Magazine

    March 8, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    Jennifer Lawrence is reinventing herself for a comeback

    March 9, 2023

    Reddit – Dive into anything

    March 9, 2023

    T-level delays: Colleges face disruption after courses are pushed back

    March 9, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.