Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shortest Code For Random Number Between 1 And N In Javascript
#1
Here I want to show you a tip for creating a random number between 1 and N in easiest and shortest way.
Code


Here is the code:

~~(Math.random () * N ) + 1

Code in textarea:


All you need to do is to replace N with your upper number.

How?
In JavaScript we have Math.random () which creates a random number between 0 and 1, e.g. 0.3577353348955512.

We use this function to have a random number, then we multiply that to our upper number (e.g. 6):

0.3577353348955512 * 6 =
2.1464120093733072

And then we get the floor number with double ~ operator
It takes so long to learn simplicity.
#2
make The Code In Textarea Sir pls
I am a proud member of NIgerian Coders Team
Reply
#3
(01-03-2017, 10:01 AM)naijaboy Wrote:
make The Code In Textarea Sir pls

Done!

***The code is just a one line code, dont know why you still need it in textarea***
I am a proud member of NIgerian Coders Team
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  SHARED: Introducing Hrouter.js Javascript Routing Library Horlahcoded 7 84 10-16-2017, 10:13 PM
Last Post: iamdannyfc
  SHARED: Introducing Hkwest.js Javascript Ajax Library Horlahcoded 0 37 10-15-2017, 09:46 AM
Last Post: Horlahcoded
  HELP: Javascript Vs Jquery. beme 10 296 08-21-2017, 07:20 AM
Last Post: beme
  HELP: Why Is This Code Not Working. Webmasters Check In! Thepreditor 6 161 08-16-2017, 09:26 PM
Last Post: jonath45
  Test Your Javascript Knowledge Dealwap 10 563 08-16-2017, 07:41 PM
Last Post: Thepreditor
  ALERT:  Webmasters Why Is This Code Not Compiling. Evinsian 7 193 08-10-2017, 09:13 AM
Last Post: Evinsian
  FUN: Let Know Who Can Get This Code Gbedu 7 162 07-08-2017, 05:58 PM
Last Post: Topkeh
  How Can I Submit A Form Using Javascript iamdannyfc 11 235 06-22-2017, 10:13 PM
Last Post: bfaschat
  TUTORIAL: Take A Selfie With Javascript SamBlingxZ 0 82 06-05-2017, 11:41 PM
Last Post: SamBlingxZ
  3 Types Of Javascript Animations That I So Much Admire! Laive 5 213 05-20-2017, 09:40 AM
Last Post: Laive



Users browsing this thread: 1 Guest(s)

About Nigeria's Creative Talents

Nigeria's Creative Talents is an online community where every creative Nigerians can share ideas with themselves.

For any more information, please use our contact form.

              User Links

              Advertise