Random numbers and shuffling
Math.random() is fine for games and layout. Use crypto for anything secret.
JavaScript · Random numbers and shufflingBeginner
const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; // inclusive
function shuffle(array) {
const a = [...array];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const dice = randInt(1, 6);
const pick = ['a', 'b', 'c'][randInt(0, 2)];
const token = crypto.getRandomValues(new Uint32Array(1))[0]; // secure valuerandomMath.randomshuffle