Hey there, fellow coders and tech enthusiasts! Today, we’re diving into the wonderful world of coding snippets. 🚀
If you’ve spent any time in the vast realm of programming, you’ve likely come across those bite-sized chunks of code that very quickly solve common problems or add nifty functionalities to your projects. We’re talking about those trusty companions that make our coding journey smoother and more efficient.
Here we’ll be exploring some of the most commonly used coding snippets, that you might require one day, whether you’re a seasoned pro or just starting your coding adventure. These snippets will surely come in handy and save you precious time and effort.
Generating a Random Number:
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Usage example
const randomNumber = getRandomNumber(1, 100);
console.log(randomNumber); // Output: Random number between 1 and 100
Here I have used a built-in function called Math.random()
that generates a pseudo-random decimal number between 0 (inclusive) and 1 (exclusive)
Math.Random()
// 0.6252474231132967
Math.Random()
// 0.03772396106405407
And when we multiply it with an integer N, it scales the range of the generated random number to be between 0 (inclusive) and N(exclusive).
Math.random()*8
// 2.27924218449437
Math.random()*80
// 13.722102542882197
(max - min + 1)
, calculates the range of possible values by subtracting the minimum value (min
) from the maximum value (max
) and adding 1(to include the upper bound). You can drop the 1 if you want to exclude the upper bound.
(5 - 0 + 1)
// 6 ==> Math.random()*6 will generate in range (0-5)
/* Without the 1 */
(5 - 0)
// 5 ==> Math.random()*5 will be in range (0-4)
The Math.floor()
function is used to round down the decimal number obtained in the previous step to the nearest integer. This ensures that the final result will be an integer.
Math.random()*5
// Will look like - 1.359376633672147
/* We need to drop the decimal part*/
Math.floor(Math.random()*5)
// 1
Math.floor(Math.random() * (max - min + 1)) + min
: Lastly, by adding the minimum value (min
) to the randomly generated integer, we shift the range to start from the minimum value and end at the maximum value. This results in a random integer within the desired range, inclusive of both the minimum and maximum values.
/* min=0, max=5 */
Math.floor(Math.random()*5)
// 2 || 3 || 0
/* To generate in a range (5-10) */
Math.floor(Math.random()*(10 - 5 + 1)) + 5
// 6 || 8 || 10
In this post, we covered generating random numbers. Remember to adapt and customize the code to suit your specific requirements. JavaScript’s versatility and these code snippets will undoubtedly elevate your coding prowess and productivity.
Top comments (0)