Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Random in JavaScript

Js Random in JavaScript

? JavaScript Random Numbers

In JavaScript, you generate random numbers using the built-in Math.random() function.


Math.random()

  • Returns a floating-point number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random()); // e.g., 0.48216367170458025

Generate Random Number in a Range

To get a random integer between two values (inclusive), use this formula:

function getRandomInt(min, max) {  min = Math.ceil(min);  max = Math.floor(max);  return Math.floor(Math.random() * (max - min + 1)) + min;}// Example: random integer between 1 and 10console.log(getRandomInt(1, 10));

Generate Random Float in a Range

function getRandomFloat(min, max) {  return Math.random() * (max - min) + min;}// Example: random float between 1.5 and 5.5console.log(getRandomFloat(1.5, 5.5));

Example: Random Color Generator

function getRandomColor() {  const r = getRandomInt(0, 255);  const g = getRandomInt(0, 255);  const b = getRandomInt(0, 255);  return `rgb(${r},${g},${b})`;}console.log(getRandomColor()); // e.g., rgb(123,45,67)

Summary

  • Math.random() returns float ?0 and <1

  • Use multiplication and rounding to get desired range


Want me to show how to shuffle an array randomly or generate random IDs?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql