Randomly load an element from a JavaScript array or object

In this exercise we will see how to randomly load an element from a JavaScript array or object. This exercise is also a JavaScript solution to our programming exercise   – Greet the guests

Randomly load an element from a JavaScript array or object – defining the javascript object named “guests” and the variables

The object stores the name of the guests and the gender

Randomly load an element from a JavaScript array or object – Randomly loading an item from the javascript object

  • We use the ‘window.addEventListener‘ method to load the function on page load.
  • We load the item randomly from the object using the ‘Math.random‘ method.
  • We store the Guest name  and gender in the respective variables.
  • We make use of the if/else statement to check the gender and store the value in the ‘title’ variable as per the requirement.

Randomly load an element from a JavaScript array or object – display the message

Finally we greet the guests by displaying the Welcome message in the header with an id “welcomeNote’ using the javascript property ‘innerHTML‘.

.