JavaScript - Get  a Random item from an Array

JavaScript - Get a Random item from an Array

Table of contents

No heading

No headings in the article.

Sometimes we need to work with random values, imagine that you have an array of items and you need to get a random value from the array.

We can start creating a function that takes an array of items as a parameter and returns a random item from the array:

function randomItem(items){
  return items[Math.floor(Math.random() * items.length)];
}

Then we can use the function created above.

let items = [1,200, 'a', 30, 'hello javascript', 50, 56, 20];

randomItem(items) // 'hello javascript'

randomItem(items) // 20

randomItem(items) // 200

Please if you know another way to do this let me know in the comments below ✌️