26: How To Create A Random Number Using JavaScript | Create A Random Number | JavaScript Tutorial

Поділитися
Вставка
  • Опубліковано 26 сер 2024
  • In this JavaScript tutorial you will learn how to create a random number using JavaScript. Generating a random number using JavaScript is a bit more complicated than you might think, since JavaScript doesn't have a simple function or method that can do it. Therefore I decided to create this seperate video that teaches you how to do it using our own JavaScript code.
    ➤ CHECK OUT THESE AWESOME PEOPLE!
    Daniel Simionescu
    Meet Daniel: another Full-Stack developer who can teach you coding fast and free :D
    / @danielsimionescu298
    Code Smarter
    Hi, I'm Code Smarter, a new content creator. I create coding tutorials and coding challenges. I promise in the upcoming weeks my channel will be filled with content. Check my channel out and subscribe.
    Link: / channel
    ➤ GET ACCESS TO MY LESSON MATERIAL HERE!
    First of all, thank you for all the support you have given me!
    I am really glad to have such an awesome community on my channel. It motivates me to continue creating and uploading content! So thank you!
    I am now using Patreon to share improved and updated lesson material, and for a small fee you can access all the material. I have worked hard, and done my best to help you understand what I teach.
    I hope you will find it helpful :)
    Material for this lesson: / lesson-material-42361704

КОМЕНТАРІ • 103

  • @TheEyesOfTheJEagle
    @TheEyesOfTheJEagle 6 років тому +52

    what is wrong with just "let getRandom = Math.floor( (Math.random() * (range - start) ) + start );
    its way easier than looping.

    • @Dani_Krossing
      @Dani_Krossing  6 років тому +16

      Yes that is a better solution that takes up less resources :)

    • @nielsencs
      @nielsencs 6 років тому +5

      TheEyesOfTheJEagle Not only that but there is zero chance of accidentally having the two lines of code not be exactly the same! Also there is no need to store the result in a variable before returning it.

    • @MichaelHallbsmbahamas
      @MichaelHallbsmbahamas 5 років тому +6

      You could also use an if statement to check if the number is higher than the range, and if so set it to be the passed in range...
      if(getRandom > range){ getRandom = range; }

    • @nuggetjimenez6921
      @nuggetjimenez6921 5 років тому +1

      TheEyesOfTheJEagle would var instead of let work?

    • @mohamedatef97
      @mohamedatef97 5 років тому +5

      I don't understand this solution, I found it in MDN, but I did not understand it .. so could please explain that solution? Especially this part >> (range - start) ) + start

  • @ozarkchinquapin6010
    @ozarkchinquapin6010 6 років тому +9

    I really really really like your videos. There are a LOT of videos out there but being able TO TEACH is a GIFT. And you, sir, have that gift. Thank you so much for all your videos and hard work.

  • @theanimalworld692
    @theanimalworld692 3 місяці тому

    This is very impressive video that I never met before. Thank

  • @grant6821
    @grant6821 2 роки тому

    this is the way to do it with less stress imo......... love the video and i learned from them
    let ran = function (start,end)
    {
    let ac_end = end - start;
    return Math.floor((Math.random() * ac_end) + start)
    }
    console.log(ran(40,50));

  • @kwartai1714
    @kwartai1714 5 років тому

    I have been looking at different java tutorials, but you are the first one to be so clear at explaining stuff, thanks

  • @comma_101
    @comma_101 Рік тому

    Thanks you this helps a lot I think Ive see this done with max and min

  • @TrungTran-rz6tz
    @TrungTran-rz6tz 5 років тому +7

    Hi everyone, just want to suggest a more "random" way of doing this, that is using Math.round() instead of Math.floor(), because that will round off the number (either up or down) rather than always round it down.
    When we use Math.floor(), then for example if we run getRandomNumber(5, 12), we will almost never get the number 12, while in theory we should get 12 every once in a while because the odd is not that low.
    The reason is that 12 only get returned if Math.random() return exactly 1, which almost never ever happen.

    • @slapmyfunkybass
      @slapmyfunkybass 5 років тому +1

      Trung Tran Not sure I agree with that as you will get 11 if the random number is above 10.5.

  • @inayatahmadzai4414
    @inayatahmadzai4414 2 роки тому

    Thank you so much it was easy to understand.

  • @swallowedinthesea11
    @swallowedinthesea11 6 років тому +4

    Nice! JS's random seems more complex than Python's random module.
    Stay safe during the Coronavirus!

  • @pacedelacruz4913
    @pacedelacruz4913 4 роки тому

    You're such an Angel. I love the way you teach. Everything is so clear and you make it so easy to understand. Thank you so much ❤️

  • @mohamedatef97
    @mohamedatef97 5 років тому

    Very useful and helpful because it helped me to make a simple generate number project.

  • @sodiqayilara1519
    @sodiqayilara1519 3 роки тому

    great great video, as a beginner, I found this useful.

  • @MylesGmail
    @MylesGmail 5 років тому +1

    Ur an awesome teacher!

  • @rasulakhundov500
    @rasulakhundov500 4 роки тому

    Thank you so much. You really good teacher!

  • @yongjung5433
    @yongjung5433 5 років тому

    Thank you for the great lessons! You have saved my day again!

  • @elkhanhamet2561
    @elkhanhamet2561 3 роки тому

    thank you

  • @yesidmartins3918
    @yesidmartins3918 5 років тому

    something that simple maths makes me wonder. the while loop is probably not need and you could just use Math.floor (Math.random() * end +1 - start) + start);
    and you would not need to run the while loop. I do like the videos, though, if it wasn't for you I would be screwed as I had to learned all of them in one week and I had never known how to program. thanks!

  • @jaabrty
    @jaabrty 6 років тому

    Well done bro, I did this before and I added it to the php sign up system. My idea was to create a membership number, then I check if it was used at the database. If not, we can save it otherwise the code have to keep running. Was it a good idea ?

  • @user-uk3ns3rz6o
    @user-uk3ns3rz6o 3 роки тому

    Maybe the did update javascript after this guide, but I prefer;
    function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
    }
    Looks more cleaner :)
    Anyway...
    Thanks for this tutorial and all before that =)

    • @sugoidxth
      @sugoidxth Рік тому

      You may have saved me with //return Math.floor(Math.random() * (max - min) ) + min;//
      tysm

  • @epi6375
    @epi6375 2 роки тому

    Hi its possible that i can get a random number via time base which is every 12am random number will be executed?

  • @Soda-stream
    @Soda-stream 3 роки тому

    Hy nice vidd, but 1 question , i want to generate number for example 123456, and the last number generate 6 to 5 to 4, than 5 going 4 .

  • @KiaSoul2023Travels
    @KiaSoul2023Travels 3 роки тому

    can we do this but instead of numbers can we use a directory in the webserver with 1000 text files and can we make output the random text file into the users browser so he can copy a random text

  • @qingyido
    @qingyido 5 років тому

    What about using shuffle arr and chose the 1st number as the random integer number? But in this way do all the numbers have equal probability?

  • @ideshmaaerdene-ochir4247
    @ideshmaaerdene-ochir4247 3 роки тому

    Hello, I've got one question for you. When you refreshing the browser the random numbers you created is still there in the console. But mine is not there, why? After refreshing the previous one is gone. What should i do? Thank you.

  • @natqe4049
    @natqe4049 6 років тому +3

    What about simple range = range - start?

    • @Dani_Krossing
      @Dani_Krossing  6 років тому +1

      Yes that would work better :) Not sure why I didn't think of that

    • @pawelpow
      @pawelpow 3 роки тому +1

      range -= start

  • @butternodes6275
    @butternodes6275 4 роки тому

    Oooooo, thank you very much.

  • @benyamadugna
    @benyamadugna 4 роки тому

    thank you !!!

  • @JPTinioMedia
    @JPTinioMedia 3 роки тому

    Say can someone write a javascript to alter a random organizer contest winner to rig it and make a certain name or line or number more likely to win ?

  • @yasminh1977
    @yasminh1977 5 років тому

    around 8.54 mints. you are replacing the 10 with 'range', saying thats the Max. number, but I got confused since you placed the 10 there for getting rid of the decimal point, not as the Maximum value...??

  • @dakku_op8279
    @dakku_op8279 3 роки тому

    So I created the numbers and I have a table of 1 to 90 stating 9 rows and 9 columns .. now I want to mark the number from the table I hav received using this function

  • @bemaat6723
    @bemaat6723 4 роки тому

    thank you.

  • @skaii4
    @skaii4 5 років тому

    Which editor do you uses

  • @jacklujimmy3023
    @jacklujimmy3023 2 роки тому

    How can I include a Number in the result?

  • @kevinjaved-ud9tl
    @kevinjaved-ud9tl Рік тому

    is there dragon sleeping at the back (sniff voices lol)

  • @Star-zf8su
    @Star-zf8su 4 роки тому

    How can I generate unique array of numbers that should not be repeated????

  • @Technologism
    @Technologism 4 роки тому

    holy crap , in python you can do all of that using one word

  • @tareqmegdadi
    @tareqmegdadi 3 роки тому

    what about non repeated random number

  • @agapitovilla55
    @agapitovilla55 4 роки тому

    how to input a random generator that get result in every two minutes from 1-80?

  • @helidrones
    @helidrones 2 роки тому

    const getRandomNumber = (from, to) => {
    return scaleNumber(Math.random(), 0, 1, from, to);
    }
    const scaleNumber(value, srFrom, srTo, trFrom, trTo) => {
    return (value - srFrom) * (trTo - trFrom) / (srTo / srFrom) + trFrom;
    }
    No loop, just O(n)

  • @Vincent-fs8ry
    @Vincent-fs8ry 6 років тому

    Php like system!

  • @lhg4ming121
    @lhg4ming121 4 роки тому

    let r = Math.random().toString(36).substring(2);
    document.write(r);
    This one is better ^^

  • @trestilo8504
    @trestilo8504 5 років тому +1

    Does anyone know how to make the number non-repeatable?

    • @pawelpow
      @pawelpow 3 роки тому

      I’m not sure but a workaround would be to inset the numbers that you picked in an array and if the generated number is already in the array then it would do the random number again until it’s new. You could do this using the do while loop. Hope this helps

  • @shahidahmad2534
    @shahidahmad2534 4 роки тому +1

    What to do for not repeat a number?

  • @AK-bf3tz
    @AK-bf3tz 9 місяців тому

    Nice breathing Besse

  • @zaggo8869
    @zaggo8869 6 років тому

    how can i center a div box with css?

    • @Dani_Krossing
      @Dani_Krossing  6 років тому +1

      Using margins :) On a side note, knowing how to center anything in CSS is some of the first CSS you learn, so if you are in doubt about this then I would recommend watching a HTML course before getting into JavaScript. It will help you further down the road in JavaScript...

  • @NERO-ez1mn
    @NERO-ez1mn 6 років тому

    senpai what is the difference between using a function getRandom() & let getRandom = function()

    • @Dani_Krossing
      @Dani_Krossing  6 років тому

      My "function" episode in this playlist explains it ;)

    • @NERO-ez1mn
      @NERO-ez1mn 6 років тому

      local and global functions

    • @bilalshuja131
      @bilalshuja131 3 роки тому

      function getRandom() : its a function declaration and function getRandom() : this is a function Expression means invoked function

    • @ultronsam1214
      @ultronsam1214 2 роки тому

      The first is a function declaration, while the second is a function expression as you are assigning it to a variable.

  • @Barript
    @Barript 3 роки тому

    why not this simple and easy :
    const getRandomNumbe r= (min, max)=>{
    return Math.floor(Math.random()* (max-min +1)+ min)}

  • @jurgis5659
    @jurgis5659 4 роки тому

    Elon that's u?!

  • @stealthbusiness
    @stealthbusiness 4 роки тому

    Thanks for putting the tutorial together. :)
    Is there a way to Password Protect online videos (UA-cam, Vimeo... etc) with some if not all of these features?
    Random Password
    Set the Expiration time or date
    Set the Total time a video can be viewed
    Set how many times the password is allowed
    Setup Password Groups
    I know it's asking a lot, if you're busy, I understand. You seem to have the skills to make it happen. Just putting it out there.

    • @szb5328
      @szb5328 4 роки тому

      Well, if you mean protecting a video that is already on UA-cam, then no. But if you mean within your own site how many times can it be viewed and such, yes, it is possible. You would need to make some sort of a view counter and then if it reaches a certain amount, I think it would be possible to lock it down or just hide it. But hey, I'm sure StackOverflow has some sort of an answer.

  • @lowercaseguy3578
    @lowercaseguy3578 3 роки тому

    was this channel mtuts....... am confused!

  • @bomnumero
    @bomnumero 5 років тому

    As would be a code with 15 tens, and each tens goes up to 25 units.

  • @niko-sd5pv
    @niko-sd5pv 6 років тому

    the first.......

  • @niko-sd5pv
    @niko-sd5pv 6 років тому

    the second

  • @Stoney_Eagle
    @Stoney_Eagle 6 років тому

    You look pretty healthy for someone who does meth haha
    Great lesson bro 👊

    • @Dani_Krossing
      @Dani_Krossing  6 років тому

      Sorry?

    • @Dani_Krossing
      @Dani_Krossing  6 років тому

      Oh because I pronounce "math" as "meth"? hehe

    • @Stoney_Eagle
      @Stoney_Eagle 6 років тому

      mmtuts No its a joke buddy doesn't matter who says it, they sound way to similar 😂

  • @niko-sd5pv
    @niko-sd5pv 6 років тому

    and the fucking third....

  • @richardvargas4950
    @richardvargas4950 5 років тому

    I can see how if you are constantly changing your start number and range number , and hate mental math that the while loop is a better solution. But this is way less code and works just the same
    let myWay = Math.floor((Math.random()*6)+5);
    console.log(myWay);

  • @calibr0636
    @calibr0636 5 років тому

    So basically Math.ceil is the opposite of Math.floor

    • @calibr0636
      @calibr0636 5 років тому

      I just did this to throw people who didn't watch the video off

    • @flooow3409
      @flooow3409 5 років тому

      ur not funny

    • @calibr0636
      @calibr0636 5 років тому

      @@flooow3409 it actually is, try it

    • @calibr0636
      @calibr0636 5 років тому

      i aint lying, bruh

    • @flooow3409
      @flooow3409 5 років тому

      @@calibr0636 you're cringe asf