Hello im new to javascript and i know what Math.floor(Math.random()) * 10; does, But what i don’t understand is why is math floor first and math random second? why dosent Math.random(Math.floor()) * 10; work?
Hi saito_inca welcome to the forum
Experimenting with a language can at times be fun, other times not so much - unless you enjoy problem solving!
You can get an idea about what is going on by checking your dev tools console. (Commonly can be opened by pressing F12)
Try
var tryone = Math.floor(Math.random()) * 10;
var trytwo = Math.random(Math.floor()) * 10;
console.log(tryone);
console.log(trytwo);
and have look
For me, when in doubt, or when frustration level peaks, I resort to checking documentation. eg.
It’s because Math.floor(…) gives you the largest integer less than or equal to the value that you give it.
With your second example that includes of Math.floor(), no value is given to it.
The first example that you gave is always going to give 0, because Math.random() is worked out first, being a value from 0 to below 1, then Math.floor turn it to zero, and finally multiplying by 10 still gives you zero.
Instead, what you’ll be wanting is to multiply the random value (0 - 0.9999999999999999) by 10, and then floor the result.
It can help to put code in to a function, which helps to restrict the details of how it does its work only to that function.
For example:
function randomLimit(limit) {
// 0 <= random value < limit
return Math.floor(Math.random() * limit);
}
function randomMax(max) {
// 1 <= random value <= max
return Math.floor(Math.random() * max) + 1;
}
function randomRange(min, max) {
// min <= random value <= max
var range = max - min + 1;
return min + Math.floor(Math.random() * range);
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.