get random of array of string in javascript

To get a random element from an array of strings in JavaScript, you can generate a random index between 0 and the length of the array, and then return the element at that index.

index.tsx
const strings = ['hello', 'world', 'program', 'code', 'javascript'];

const randomIndex = Math.floor(Math.random() * strings.length);

const randomString = strings[randomIndex];

console.log(randomString); // output: a random element from the array
249 chars
8 lines

This code uses the Math.random() method to generate a random number between 0 and 1, multiplies it by the length of the array to get a number between 0 and the last index of the array, and then rounds it down using the Math.floor() method to get an integer. Finally, it retrieves the element at that index to get a random string from the array.

gistlibby LogSnag