1

How can I randomize a variable in JavaScript between 0-4, so that every time the page loads the variable is different but between 0 and 4?

2 Answers 2

6

You can use Math.random() for this. To get a (whole) number between 0 and 4 inclusive, use the following:

var random = Math.floor(Math.random() * 5);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the fast reply's! Worked a charm!
3
// Returns a random integer between min and max  
function getRandomInt(min, max)  
{  
  return Math.floor(Math.random() * (max - min + 1)) + min;  
}

from mdc (mozilla developer center)

2 Comments

You missed the link in my answer? :)
but fell in love with the typography, so can't delete now. But hey, people vote to BalusC :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.