Math.random
Returns a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1
Syntax
Math.random()Return Value
A pseudo-random number between 0 (inclusive) and 1 (exclusive)
Examples
console.log(Math.random()); // e.g. 0.7342...function randomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100)); // 1-100function shuffle<T>(arr: T[]): T[] {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
console.log(shuffle([1, 2, 3, 4, 5]));Understanding Math.random
The Math.random method in JavaScript returns a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1. It belongs to the Math object and is one of the most widely used methods for working with math values in modern JavaScript and TypeScript applications.
The method signature is Math.random(). When called, it returns a pseudo-random number between 0 (inclusive) and 1 (exclusive). Understanding when and how to use random() helps you write more expressive, readable code.
Common use cases for Math.random include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like math-floor, math-round, math-ceil, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Math.random is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Math Methods
Other methods in the Math object
Related Tools
More Math Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.