How to randomize values in JavaScript. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to randomize values in JavaScript.

For example: Let`s pretend i want to make a code for creating a conversation between the user and the program. var answer =["I am a program", "I am a software", "I am a JavaScript program"]; function dialogue() { alert("Hello there"); var user = prompt("Say something"); if(user == "What are you?") { alert(answer); } In the alert above i`d like the program to randomly select one of the strings inside the answer array and print it. }

28th Nov 2016, 3:16 PM
Silas Junior
Silas Junior - avatar
4 Answers
+ 4
It's really simple: Math.random () this gives you a number between 0 and 1 Math.random ()*100 this gives you a number between 0 and 100 Math.floor (Math.random()*100) this gives you a ROUNDED number between 0 and 100 hope this helps ~Kamil
28th Nov 2016, 3:28 PM
Kamil
Kamil - avatar
+ 4
Tha you, man. I think this will do.
28th Nov 2016, 3:30 PM
Silas Junior
Silas Junior - avatar
+ 2
Maht.random returns a random number between 0 (inclusive) and 1 (exclusive). Math.random() will never return the value 1. So, Math.floor(Math.random()*100) will return a value between 0 and 99. And Math.floor(Math.random()*101) will return a value between 0 and 100. If you want to work with an interval, you can do: Math.floor(Math.random()*6)+5 It will return a value between 5 (inclusive) and 10 (inclusive). You can also do: Math.floor(Math.random()*11)*10 It will return one of this values: 0, 10, 20, 30, ..., 100. Good luck!
28th Nov 2016, 7:09 PM
Thiago Santos
Thiago Santos - avatar
+ 2
yes Math.random() gives you random no brtwwn 0 to 1 you can multiply it by no of elements you want and round off using Math.floor() so for one digit Math.floor(Math.random*10);
28th Nov 2016, 7:17 PM
Sandeep Chatterjee