0

I'm trying to make an alert box pop up with one random sentence from an array of sentences inside it. This is my code:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) - 1);

alert(tasks[randomTask]);

If you run it, the only thing the pop says is "undefined". Why doesn't it work?

Thanks to anyone that answers! :-)

1
  • Actually when (Math.random() * tasks.length) gives 1 then you are subtracting with 1 and then it should be 0 and the floor of 0 is -1. so when you accessing -1 property of array you are getting undefined. Commented Sep 11, 2015 at 11:19

3 Answers 3

4

Math.random returns a random number between 0 (inclusive) and 1 (exclusive), you multiply it by 3 and subtract 1, so you can get a number between -1 and 2 (where 2 is exclusive - value will always be lower than 2). And when you floor a negative value, you get -1. That's why you get undefined sometimes

Basically, remove - 1 and it should work

Sign up to request clarification or add additional context in comments.

1 Comment

Then can't I just remove the -1?
2

The reason is that, the Math.random() returns a number between 0 and 1.

When the number is 0.1xxx, it is

computed as

0.1xxxxx * 3 - 1

that is

Math.floor(0.3xxxx - 1) = -1

And array[-1] is undefined.

To get around this issue, you can use % operator on the resulting random number. % will ensure that the number is always between 0 and arr.length - 1.

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var randomTask = Math.floor((Math.random() * tasks.length) % tasks.length);

alert(tasks[randomTask]);

Comments

1

This will do:

var tasks = [
  "This is the first task",
  "And this is the second task",
  "Third task..."
];

var rand = Math.floor(Math.random() * ((tasks.length -1) - 0 + 1)) + 0;
alert(tasks[rand]);

2 Comments

How is ((tasks.length -1) - 0 + 1) any different from tasks.length?
And why would you ever + 0 or - 0?

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.