New projects and new features are going to be added soon. I am working on it, finally have some time. If you have any questions or suggestions, please contact me: workit.js@gmail.com. Currently I am working on BoostBalls project explanation.

This is a free project, and in order for it to continue being free, please consider supporting it.

Random value from array

Function ready to be used

const getNum = (...nums) => nums[Math.floor(Math.random() * nums.length)]; 

Get last element from array

Read this Math.random() if you don't know about it.

Each element in array has own index string from 0. That means each index equals element position - 1 if count normal starting from 1.

To find the index of the last element in an array, we just need to take the array's length, which represents the normal position of the element, and subtract 1 from it.

const array = [10, 12, 33, 24, 45, 63, 72, 18]; 
const lastElemntIndex = array.length - 1; 

console.log(lastElemntIndex); // 7

Now to get first element we just need to pass 0 into brackets array[0] and to get last element we need to pass array.length - 1 into brackets array[array.length - 1]

const array = [10, 12, 33, 24, 45, 63, 72, 18]; 
const lastElemntIndex = array.length - 1; 
const lastElemnt = array[lastElemntIndex]; 

console.log(lastElemnt); // 18

Get random element from array

We already know that when we use Math.random(), it returns a number between 0 and 1 (1 is excluded). If we multiply Math.random() by a number, we can get a value between 0 and that number (not including that number).

That is exactly what we want. If we multiply Math.random() by array.length then we'll get value between 0 and array.length - 1 which represents the index of last element.

However, there is one thing to keep in mind.Math.random() gives us a number with decimals, but array indices are whole numbers (integers). So, we should use Math.floor() to round down the result to a whole number.

Here's how you can do it:

const array = [10, 12, 33, 24, 45, 63, 72, 18]; 
const randomElement = array[Math.floor(Math.random() * array.length)]; 

console.log(randomElement); // 72

With this code, we can easily pick a random element from the array.

Creating a Reusable Function

Let's make a function to reuse code in the future.

function randNum(array){
  const randomElement = array[Math.floor(Math.random() * array.length)]; 
  return randomElement; 
}

const array = [10, 12, 33, 24, 45, 63, 72, 18]; 

console.log(randNum(array)); // 72

Simplified Function

Now we know how to randNum() works inside. Let's make it smaller.

const getNum = (...nums) => nums[Math.floor(Math.random() * nums.length)]; 

...nums is restoperation. It gathers all value into array. func(1, 2, 3) into func([1, 2, 3]). Now we don't need to pass array into function randNum([1, 2, 3]). We can just pass it like this randNum(1, 2, 3)