Crypto

crypto.getRandomValues

Fills the provided typed array with cryptographically strong random values

Syntax

JavaScript
crypto.getRandomValues(typedArray)

Parameters

ParameterTypeDescription
typedArrayTypedArrayAn integer-based TypedArray to fill with random values

Return Value

The same typed array passed in, now filled with random values

Examples

Basic Usage
const array = new Uint8Array(16)
crypto.getRandomValues(array)
console.log(array)
Practical Example
function randomInt(min: number, max: number): number {
  const range = max - min
  const array = new Uint32Array(1)
  crypto.getRandomValues(array)
  return min + (array[0] % range)
}
Advanced Usage
function generateToken(length: number): string {
  const bytes = new Uint8Array(length)
  crypto.getRandomValues(bytes)
  return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
}

Understanding crypto.getRandomValues

The crypto.getRandomValues method in JavaScript fills the provided typed array with cryptographically strong random values. It belongs to the Crypto object and is one of the most widely used methods for working with crypto values in modern JavaScript and TypeScript applications.

The method signature is crypto.getRandomValues(typedArray). It accepts 1 parameter: typedArray. When called, it returns the same typed array passed in, now filled with random values. Understanding when and how to use getRandomValues() helps you write more expressive, readable code.

Common use cases for crypto.getRandomValues include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like crypto-randomuuid, math-random, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for crypto.getRandomValues 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 Crypto Methods

Other methods in the Crypto object

Related Tools

More Crypto Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.