Pick a random member from a JavaScript array
Let's learn about this useful approach with arrays in JavaScript
By: Ajdin Imsirovic 06 January 2021
The trick to doing this: multiply array’s length with a Math.random()
call, then floor the resulting number.
We’ll start with an array consisting of just two numbers: 1
and 2
.
1
2
3
4
5
6
7
const arr = [1, 2]
const randomItem = arr => {
let randomize = arr[Math.floor(Math.random() * arr.length)];
console.log(randomize);
return randomize;
}
randomItem(arr) // returns 1 or 2 all the time
Now we can use any array we want:
1
['apple','pear','mango','kiwi','lemon'];
We’ll pick a random number from this array using the combination of the length
property and the Math.random()
method, all wrapped in an IIFE.
1
2
3
4
5
6
7
8
9
(function() {
const arr = ['apple','pear','mango','kiwi','lemon'];
const randomItem = arr => {
let randomize = arr[Math.floor(Math.random() * arr.length)];
console.log(randomize);
return randomize;
}
randomItem(arr);
})();
Why use an IIFE above? Why not just write our code like below?
1
2
3
4
5
6
7
const arr = ['apple','pear','mango','kiwi','lemon'];
const randomItem = arr => {
let randomize = arr[Math.round(Math.random() * arr.length)];
console.log(randomize);
return randomize;
}
randomItem(arr);
Because when we run the above code in the console, it will work fine. However, if we try to reassign any const
values after we’ve already run our code, we’ll get the following error:
You might say that I’m a bit opinionated, but for me it’s a lot easier to not pollute the global scope, and instead use this simple IIFE trick.
Alternatively, we can just open a new tab, which opens a new JS environment that we can interact with using the devtools console.
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.