Return 5 random numbers in range, first number cannot be zero - JavaScript

We are required to write a JavaScript function that generates an array of exactly five unique random numbers. The condition is that all the numbers have to be in the range [0, 9] and the first number cannot be 0.

Example

Following is the code ?

const fiveRandoms = () => {
    const arr = []
    while (arr.length < 5) {
        const random = Math.floor(Math.random() * 10);
        if (arr.indexOf(random) > -1){
            continue;
        };
        if(!arr.length && !random){
            continue;
        }
        arr[arr.length] = random;
    }
    return arr;
};
console.log(fiveRandoms());

Output

This will produce the following output in console ?

[ 9, 0, 8, 5, 4 ]

How It Works

The function uses a while loop to generate random numbers until we have exactly 5 unique numbers:

  • Math.floor(Math.random() * 10) generates numbers from 0 to 9
  • arr.indexOf(random) > -1 checks if the number already exists in the array
  • !arr.length && !random prevents zero from being the first number
  • arr[arr.length] = random adds the valid number to the array

Alternative Approach Using Set

Here's a more modern approach using Set for uniqueness:

const fiveRandomsWithSet = () => {
    const numbers = new Set();
    
    // First number (1-9 to avoid zero)
    numbers.add(Math.floor(Math.random() * 9) + 1);
    
    // Remaining four numbers (0-9)
    while (numbers.size < 5) {
        numbers.add(Math.floor(Math.random() * 10));
    }
    
    return Array.from(numbers);
};

console.log(fiveRandomsWithSet());
[ 7, 2, 8, 0, 3 ]

Comparison

Method Uniqueness Check Performance Code Clarity
While Loop + indexOf Array.indexOf() Good More verbose
Set Approach Set built-in Better Cleaner

Conclusion

Both approaches generate 5 unique random numbers with the first number being non-zero. The Set method is more modern and efficient for ensuring uniqueness.

Updated on: 2026-03-15T23:18:59+05:30

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements