javascript / beginner
Snippet
Generating Random Integers
Math.random() returns a decimal between 0 and 1. By multiplying it by 10 and using Math.floor(), we can create a random integer between 1 and 10.
snippet.js
1
2
const randomNum = Math.floor(Math.random() * 10) + 1;console.log(randomNum);
nodejs
Breakdown
1
Math.random() * 10
Generates a random decimal between 0 and 9.99.
2
Math.floor(...) + 1
Rounds down to the nearest integer and adds 1 to adjust the range to 1-10.