How to Generate Random Nouns in JavaScript
How to Generate Random Nouns in JavaScript

Introduction to Generating Random Nouns

In JavaScript knowing how to generate random nouns is very important across a multiple applications, For Example let’s take game development, random noun generation can be used to generate unique and dynamic in-game content, i.e. character names, item lists, or may be even story elements.

The process of generating random nouns in JavaScript involves several key steps:

  • First, create list of nouns from which to generate random nouns will be picked It can be array of noun words or if you want nouns to be picked from any external source like database or API.
  • Second, We will be using JavaScript Built-In Method to randomly pick a number then pick a randon number from the array list index.
  • Finally, The selected noun can be used to show in frontend application.

Building the Random Noun Generator

Below is source code to randomly pick noun basically Noun Generator on js.

Below is an array that contain list of nouns:

const nouns = ["apple", "banana", "car", "dog", "elephant", "flower", "guitar", "house", "ice", "jacket"];

With our array of nouns in place Perfectly, Next is we need to write a javascript function that randomly generate a number that is between the array list length by using JavaScript provides a built-in method, i.e. Math.random(), Then Finally return the noun from the array list using random index number . Here’s a simple function that accomplishes this:

function getRandomNoun() {
  const randomIndex = Math.floor(Math.random() * nouns.length);
  return nouns[randomIndex];

In the function getRandomNoun(), we make use Math.random() method to generate a random number between 0 and 1 it will be in decimal 0.01 to 1.0 and then Multiplying this number by the length of the array. Then to make roundup of the number we can use Math.floor() it will round the number to nearest whole number, ensuring it is a valid index. Finally, we return the noun located at this index in the array.

Now simply call the function whenever you need a random noun:

console.log(getRandomNoun()); // Output might be "dog"

In above code in implemented list of Nouns in code itself. That means if we want to add more nouns in the list we need to manually make update to the code. There to enhance the generation on Noun it’s better to dynamically get/fetch the array list from external source like API or Database then pick random noun from the dynamic array list. Below is basic snippet code for reference.

  .then(response => response.json())
  .then(data => {
    nouns = => item.word);