Everybody! This is important. In a few days, these forums will be moving over to using the totally sweet Discourse platform. To ensure this migration happens smoothly with no loss of content, these forums are currently in a read-only mode. I do apologize for the inconvenience.

There is never a good time to turn the forums off for an extended period of time, but I promise the new forums will be a billion times better. I'm pretty sure of it.

See you all on the other side in a few days, and if you have any (non-technical) questions, please e-mail me at kirupa@kirupa.com. For technical questions, try to find a tutorial that corresponds to what you are looking for and post in the comments section of that page.

Cheers,
Kirupa

Results 1 to 3 of 3

Thread: return with javascript

  1. #1

    return with javascript

    Hello,

    I wish to make a variable which is a function that returns a random number when run.

    for simple simon's sake, here is a silly example ..
    Code:
    var ran = function(){
       Math.random()*1;
       return;
    }
    
    console.log(ran); // gives me my random number
    AND
    console.log(ran+" "+ran); // gives me two different random numbers
    Can someone help my syntax!?
    Thanks

  2. #2
    Code:
    var ran = function () {
        return Math.random();
    }
    Have a look at this tutorial: Random Numbers in JavaScript

  3. #3
    Quote Originally Posted by jeancnicolas View Post
    Can someone help my syntax!?
    Further to jeancnicolas' example you need to use the brackets () to invoke the function:
    Code:
    var ran = function(){
       return Math.random()*1;
    }
    
    console.log(ran()); // gives me my random number
    AND
    console.log(ran()+" "+ran()); // gives me two different random numbers
    Quote Originally Posted by jeancnicolas View Post
    I wish to make a variable which is a function that returns a random number when run.
    There are a few things to keep in mind with the random number generator in JavaScript in that it's not truly random and if you are intending on using it where you want to be able to seed your own random numbers you can't (JavaScript seeds it's own random generator with the current time).

    Further reading:
    http://blog.ginchen.de/en/2010/10/09...ll-keiner-ist/
    http://stackoverflow.com/questions/1...ts-math-random

    There are a few implementations I've seen for the Mersenne Twister algorithm if you need a number that is more truly random.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012