Explore this detailed JavaScript tutorial, encompassing topics like creating and editing arrays, and using the Math object to pick a random item from an array in an exercise context.
This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.
Topics covered in this JavaScript tutorial:
Creating an array, Editing an array, The Math object, Picking a random item from an array
Exercise Preview
Exercise Overview
In this exercise, you’ll learn about arrays. You’ll also learn about the Math object and how to use it in conjunction with arrays to display the values we want.
Getting Started
- For this exercise we’ll be working with the Random-Testimonial folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
- In your code editor, open index.html from the Random-Testimonial folder.
- Preview index.html in Chrome. (We’ll be using its DevTools.)
-
Notice the testimonial NAPS is by far the most significant cultural force of the decade. – New York Times.
We want to use JavaScript to randomly show a different testimonial each time the page is loaded. In order to accomplish this, we’ll be using an array. Think of an array as a list. We can store multiple values in a single array. The array stores items in a numbered list, so we can access any specific value by referring to its number (index) within the list. While you typically number lists starting with 1 (then 2, 3, etc.), JavaScript arrays start with 0 (then 1, 2, etc).
Creating an Array
Before we start working on this page, let’s first learn the fundamentals about arrays by experimenting in the Console. We’ll start by create an array. To open Chrome’s Console, hit Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
-
In the Console, type the following but do not hit Return/Enter yet!
let myArray = []
NOTE: The
[]
denotes an array in JavaScript. -
So far our array is empty. Add some values to the array as shown in bold:
let myArray = ['Madrid', 'Paris', 'London']
- Hit Return (Mac) or Enter (Windows) to apply it.
-
The Console will print undefined, but do not be concerned.
NOTE: Why does it say undefined? Some things in JavaScript return a result when they are executed. Creating an array does not return a value, so the return is undefined. In this case we don’t care about a returned value, so you can proceed.
- Type
myArray
and hit Return (Mac) or Enter (Windows). - You should see
['Madrid', 'Paris', 'London']
print out in the Console. -
How do we get a specific value from this array? To get the first value, type:
myArray[0]
NOTE: Remember that arrays are zero-indexed, which means they start numbering with 0.
Hit Return (Mac) or Enter (Windows) to apply it and the string
'
Madrid'
will print.-
To get the third value, type:
myArray[2]
TIP: You can hit your Up Arrow key to reload the previous Console command.
Hit Return (Mac) or Enter (Windows) and the string
'
London'
will print.
Editing an Array
-
To change a value in an array, type:
myArray[2] = 'Beijing'
Hit Return (Mac) or Enter (Windows) and ‘Beijing’ will print.
-
Arrays have a variety of methods and we want to test out some of the commonly-used methods. Type the following so we can look at these methods:
console.dir(myArray)
NOTE: dir displays an interactive list of an object’s properties. It stands for directory, as in an informational directory.
Hit Return (Mac) or Enter (Windows).
-
Expand the array’s list by clicking the arrow to the left of Array(3).
Notice it says the length is 3 (this is how many values are in the array).
-
Click the arrow next to [[Prototype]]: Array(0).
Here you see a list of methods we can use. For example, find push and sort. Let’s try some.
-
What if we want to add a value to the array? To do this, type the following code:
myArray.push('New York')
NOTE: You can put any value you want to add in the parentheses. Here, we’re adding the value
'New York'
to the array. Hit Return (Mac) or Enter (Windows). It prints 4 to show how many values are in the array.
-
Type
It will show the values in the array:myArray
and hit Return (Mac) or Enter (Windows).
['Madrid', 'Paris', 'Beijing', 'New York']
-
Checking how many values are in an array is very useful when writing dynamic code. To test it out, type the following:
myArray.length
Hit Return (Mac) or Enter (Windows) and 4 will print.
-
Sometimes it’s useful to sort an array. JavaScript arrays have a
sort()
method that will work here. To test it out, type the following:myArray.sort()
-
Hit Return (Mac) or Enter (Windows) and the Console should print the cities in alphabetical order:
['Beijing', 'Madrid', 'New York', 'Paris']
Leave index.html open in Chrome so we can come back to it later.
Creating an Array of Testimonials
Now that we’ve seen a bit of what arrays can do, let’s get to work on replacing the static testimonial on the page with an array of various press quotes.
- Switch back to index.html in your code editor.
-
Start adding a new array before the closing
</body>
tag:</footer> <script> let quotes = []; </script> </body>
-
Inside the
[]
brackets, add some quotes by adding the following bold code:<script> let quotes = [ 'first quote', 'second quote', 'third quote' ]; </script>
NOTE: Our values are strings, so each quote must be wrapped in single quotes. Note that each is separated by a comma, but there’s no comma after the last.
- Save and reload the page in Chrome.
- Open the Console if it’s not already open.
- Type
quotes
and hit Return (Mac) or Enter (Windows). You’ll see the quotes printed. - Now we need to figure out how to switch out the testimonial on the page. Go back to your code editor.
- Around line 34, notice that we’ve given the testimonial p tag an ID of press-quote.
- Let’s see if we can change the testimonial using the Console. Switch back to Chrome.
-
In the Console, let’s grab the press-quote element:
document.getElementById('press-quote')
- Hit Return (Mac) or Enter (Windows) to apply it.
- It should print the HTML element (the entire tag and it’s contents). We only want the text inside the element though.
- Hit your Up Arrow key to reload the previous command.
-
At the end, add .innerHTML so you end up with the following:
document.getElementById('press-quote').innerHTML
- Hit Return (Mac) or Enter (Windows) to apply it.
-
It should print the text string content:
"NAPS is by far the most significant cultural force of the decade. — New York Times"
- Let’s try to change that text. Hit your Up Arrow key to reload the previous command.
-
At the end, add = quotes[2] so you end up with the following:
document.getElementById('press-quote').innerHTML = quotes[2]
NOTE: In this case, we’re changing the text of the testimonial to the third quote in the array. Remember that JavaScript arrays start counting with 0!
-
Hit Return (Mac) or Enter (Windows) and notice the testimonial on the page now says third quote!
Now that we know how to change the testimonial text, we need to find a way to choose a random testimonial.
The Math Object
The Math object contains a lot of very helpful functions for doing various mathematical operations. Let’s investigate to see if it can help us.
In the Console, type
Math
and hit Return (Mac) or Enter (Windows).-
Click the arrow next to Math (the Math object) to expand it. In it, you can see its properties and functions.
The list starts off with constants (values that are not meant to be changed), such as
PI
. Constants are written in UPPERCASE. So for example, if you ever needed to do a mathematical operation that involvesPI
, typeMath.PI
and it will give you the value ofPI
. -
What we’ll be focusing on right now is the random() method. Type:
Math.random()
Hit Return (Mac) or Enter (Windows). It’ll print a random number between 0 and 1.
- Hit the Up Arrow key to reload Math.random().
-
Hit Return (Mac) or Enter (Windows) to see it generates a different random number.
How can we apply this to our project? We can have JS choose a random number within a certain range. Then we use that number to choose an item from the quotes array. If we have 5 testimonials, we’d tell it to pick a number between 0 and 4.
-
To get a random number between 0 and 4, type the following code:
Math.random() * 4
NOTE: This multiplies the random number by 4 so instead of getting a number between 0 and 1, it outputs one between 0 and 4.
-
Hit Return (Mac) or Enter (Windows) to see a random number between 0 and 4.
One problem is that the number we get has many decimal places, but we need an integer (a whole number).
-
The Math.floor() method rounds down to the closest whole number. Type:
Math.floor(3.78)
Hit Return (Mac) or Enter (Windows) and it’ll print out 3.
-
The Math.ceil() function rounds up to the closest whole number. Type:
Math.ceil(3.78)
Hit Return (Mac) or Enter (Windows) and it’ll print out 4.
Using the Math Object to Pick Random Testimonials
Now that we know how the Math object works, let’s figure out how we can customize it for our purposes.
- Switch back to your code editor.
- First, let’s add the actual press quotes to our array. We’ve already typed out the quotes for you. Go into the snippets folder and open press-quotes.txt.
- Select and copy all the text.
- Close the file. If you aren’t already in index.html, switch to it.
- Select the 3 placeholder quotes.
- Replace them by pasting the new quotes over them.
- Save and reload the page in Chrome.
-
In the Console, type the following code but do not hit Return/Enter yet!
Math.random() * quotes.length
This says to take a random number between 0 and 1 and multiply it by the length of the array. We could specify a certain number to multiply by (such as when we used 4 previously) but it’s better to use a dynamic number. That way if the number of items in the array changes, you won’t have to rewrite the JavaScript.
-
To round it down, wrap the line in a Math.floor() as shown below in bold (don’t miss the end parenthesis):
Math.floor( Math.random() * quotes.length)
- Hit Return (Mac) or Enter (Windows) to apply the command. You should get a random integer between 0 and 4.
- Hit the Up Arrow key and then hit Return (Mac) or Enter (Windows) to get another random integer.
-
Perfect! Now we can add this to our page. Copy the line you typed in the Console:
Math.floor(Math.random() * quotes.length)
-
Back in your code editor, in the script tag near the bottom, make a new line below the array and paste the code, as shown in bold:
]; Math.floor(Math.random() * quotes.length); </script>
-
To make this number easier to refer to, let’s store it in a variable. Add the following code shown in bold:
]; let randomNum = Math.floor(Math.random() * quotes.length); </script>
-
Next we need to grab the testimonial that’s currently on the page and replace it with a random one. Add the following bold code (as a single line of code):
let randomNum = Math.floor(Math.random() * quotes.length); document.getElementById('press-quote').innerHTML = quotes[randomNum]; </script>
-
Save and reload the page in Chrome.
The page will randomly display one of the testimonials.
-
Reload the page a few more times to see a random testimonial each time. Cool!
NOTE: We are leaving the static quote in the HTML as a graceful fallback in case a visitor has JavaScript turned off (and for SEO purposes).