Introduction to Arrays & the Math Object

Free JavaScript & jQuery Tutorial

Learn about manipulating arrays and using the Math object in JavaScript & jQuery through this detailed tutorial, which includes creating an array, editing an array, and picking a random item from an array.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Creating an array, Editing an array, The Math object, Picking a random item from an array

Exercise Preview

ex prev random testimonial

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

In this exercise, we will learn about arrays and how to create them. We’ll also learn about Math objects and how to use them in conjunction with arrays to display the values we want.

Getting Started

  1. Open your code editor if it isn’t already open.
  2. Close any files you may have open.
  3. For this exercise we’ll be working with the Random-Testimonial folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).
  4. Open index.html from the Random-Testimonial folder.
  5. Preview index.html in Chrome (we’ll be using its DevTools later).
  6. 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

  1. 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).

  2. In the Console, type the following but do not hit Return/Enter yet!

    var myArray = [];
    

    NOTE: The [] denotes an array in JavaScript.

    TIP: Adjusting the Console’s Text Size

    You can adjust the size of the Console text as follows:

    • Mac: Cmd-Plus(+) enlarges the text. Cmd-Minus(-) reduces the text. Cmd-0 resets to the default size.
    • Windows: Ctrl-Plus(+) enlarges the text. Ctrl-Minus(-) reduces the text. Ctrl-0 resets to the default size.
  3. So far our array is empty. Add some values to the array as shown in bold:

    var myArray = ['Madrid', 'Paris', 'London'];
    
  4. Hit Return (Mac) or Enter (Windows) to apply it.
  5. The Console will print undefined, which is something we are not concerned with now.

    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 to the next step.

  6. Type myArray; and hit Return (Mac) or Enter (Windows).
  7. You should see ["Madrid", "Paris", "London"] print out in the Console.
  8. 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.

  9. Hit Return (Mac) or Enter (Windows) to apply it and the string "Madrid" will print.

  10. To get the third value, type:

    myArray[2];
    

    TIP: You can hit your Up Arrow key to reload the previous Console command.

  11. Hit Return (Mac) or Enter (Windows) and the string "London" will print.

Editing an Array

  1. To change a value in an array, type:

    myArray[2] = 'Beijing';
    
  2. Hit Return (Mac) or Enter (Windows) and “Beijing” will print.

  3. 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.

  4. Hit Return (Mac) or Enter (Windows).

  5. Expand the array’s list by clicking the arrow to the left of Array[3].

  6. Click the arrow next to __proto__: Array[0] to see the methods we can use. Let’s try some of these.

  7. 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.

  8. Hit Return (Mac) or Enter (Windows). It prints 4 to show how many values are in the array.

  9. Type myArray; and hit Return (Mac) or Enter (Windows) and it will show the values in the array:

    ["Madrid", "Paris", "Beijing", "New York"]
    
  10. Checking how many values are in an array is very useful when writing dynamic code. To test it out, type the following:

    myArray.length;
    
  11. Hit Return (Mac) or Enter (Windows) and 4 will print.

  12. 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();
    
  13. Hit Return (Mac) or Enter (Windows) and the Console should print the cities in alphabetical order:

    ["Beijing", "Madrid", "New York", "Paris"]
    
  14. 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.

  1. Switch back to index.html in your code editor.
  2. Start adding a new array before the closing </body> tag (on line 46):

    </footer>
    <script>
       var quotesArray = [];
    </script>
    </body>
    
  3. Inside the [] brackets, add some quotes by adding the following bold code:

    <script>
       var quotesArray = [
          'first quote',
          'second quote',
          'third quote'
       ];
    </script>
    

    NOTE: Our values are strings, so each quote must be surrounded by single quotes. Note that each string is separated by a comma, but there’s no comma after the last string.

  4. Save the file.
  5. Switch to index.html in Chrome and reload the page.
  6. Open the Console if it’s not already open.
  7. Type quotesArray; and hit Return (Mac) or Enter (Windows). You’ll see the quotes printed.
  8. Now we need to figure out how to switch out the testimonial on the page. Go back to index.html in your code editor.
  9. On line 32, notice that we’ve given the testimonial p tag an ID of press-quote.
  10. Let’s see if we can change the testimonial using the Console. Switch back to Chrome.
  11. In the Console, let’s grab the press-quote element:

    document.getElementById('press-quote');
    
  12. Hit Return (Mac) or Enter (Windows) to apply it.
  13. It should print the HTML element (the entire tag and it’s contents). We only want the text inside the element though.
  14. Hit your Up Arrow key to reload the previous command.
  15. At the end, add .textContent so you end up with the following:

    document.getElementById('press-quote').textContent;
    
  16. Hit Return (Mac) or Enter (Windows) to apply it.
  17. It should print the text string content:

    "NAPS is by far the most significant cultural force of the decade. — New York Times"
    
  18. Let’s try to change that text. Hit your Up Arrow key to reload the previous command.
  19. At the end, add = quotesArray[2] so you end up with the following:

    document.getElementById('press-quote').textContent = quotesArray[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!

  20. 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.

  1. In the Console, type Math; and hit Return (Mac) or Enter (Windows).

  2. 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 involves PI, type Math.PI; and it will give you the value of PI.

  3. What we’ll be focusing on right now is the random() method. Type:

    Math.random();
    
  4. Hit Return (Mac) or Enter (Windows). It’ll print a random number between 0 and 1.

  5. Hit the Up Arrow key to reload Math.random();.
  6. Hit Return (Mac) or Enter (Windows) to see it generates a different random number.

    How can we apply this for our purposes? We can have JavaScript choose a random number within a certain range that we specify. Then we can use that number to choose an item from the quotes array. If we have five different testimonials, we’d tell it to pick a number between 0 and 4.

  7. 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.

  8. 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).

  9. The Math.floor() method rounds down to the closest whole number. Type:

    Math.floor(3.78);
    
  10. Hit Return (Mac) or Enter (Windows) and it’ll print out 3.

  11. The Math.ceil() function rounds up to the closest whole number. Type:

    Math.ceil(3.78);
    
  12. 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.

  1. Switch back to your code editor.
  2. First, let’s add the actual press quotes to our array. We’ve saved you some time by typing out the quotes for you. Go into the snippets folder and open press-quotes.txt.
  3. Select and copy all the text.
  4. Close the file. If you aren’t already in index.html, switch to it.
  5. Select the three placeholder quotes.
  6. Replace them by pasting the new quotes over them.
  7. Save the file.
  8. Switch back to Chrome, and reload index.html.
  9. In the Console, type the following code but do not hit Return/Enter yet!

    Math.random() * quotesArray.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.

  10. 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() * quotesArray.length);
    
  11. Hit Return (Mac) or Enter (Windows) to apply the command. You should get a random integer between 0 and 4.
  12. Hit the Up Arrow key and then hit Return (Mac) or Enter (Windows) to get another random integer.
  13. Perfect! Now we can add this to our JavaScript. Select and copy the line you typed in the Console:

    Math.floor(Math.random() * quotesArray.length);
    
  14. Switch back to index.html in your code editor.
  15. In the script tag near the bottom of the document, make a new line below the array and paste the code, as shown in bold:

       ];
       Math.floor(Math.random() * quotesArray.length);
    </script>
    
  16. To make this number easier to refer to, let’s store it in a variable. Add the following code shown in bold:

       ];
       var randomNumber = Math.floor(Math.random() * quotesArray.length);
    </script>
    
  17. 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):

       ];
       var randomNumber = Math.floor(Math.random() * quotesArray.length);
       document.getElementById('press-quote').textContent = quotesArray[randomNumber];
    </script>
    
  18. Save the file.

  19. Preview index.html in Chrome. (Reload if it’s already open.)

    The page will randomly display one of the testimonials.

  20. Reload the page a few more times to see a random testimonial each time. Cool!

    NOTE: We are leaving the static — New York Times quote in the HTML as a graceful fallback in case a visitor has JavaScript turned off (and for SEO purposes).

Optional Bonus: Adding Quote Marks Around the Testimonial

The testimonial is looking good, but technically it contains both a testimonial and an attribution. It would be nice if the testimonial portion was surrounded by quotation marks. The testimonial and attribution are separated by an emdash. If you’re not familiar with an emdash, it’s longer than a typical hyphen. We can use JavaScript to split the string on that emdash, and then add quote marks to just the testimonial portion.

  1. Switch back to index.html in your code editor.

  2. The split() method will split a single string into an array of strings. We can specify the character (in this case an emdash) where we want to split the string. Let’s test how split() works. Around line 57, add the following bold code:

       document.getElementById('press-quote').textContent = quotesArray[randomNumber];
       console.log( quotesArray[randomNumber].split('') );
    </script>
    
  3. Inside the single quotes of the split method, you’ll need to type an em dash () as follows:

    • Mac: Hit Shift–Opt–Hyphen(-)
    • Windows: Hold Alt as you type 0151 (on the Keypad) and then release Alt. If it doesn’t work, hit the Num Lock key and try again.

    You should end up with the following code:

    console.log( quotesArray[randomNumber].split('') );
    
  4. Save the file.
  5. Switch to index.html in Chrome.
  6. Reload the page.
  7. Open the Console if it’s not already open.
  8. You’ll see the new array of testimonial strings, such as the example below.

    ["NAPS has ushered in a new era of sleep. ", " USA Today"]
    

    Take note that split() has removed the emdash, and created two items in an array.

  9. Expand the array’s list by clicking the arrow on the left.

    We can see that this array has two values, the testimonial (index 0) and the attribution (index 1).

    You’ll also notice a space at the end of the testimonial and at the beginning of the attribution. Because we only want to add quote marks at the testimonial, let’s change how we’re splitting the string to get a value containing just the testimonial.

  10. Return to index.html in your code editor.

  11. Add a space on both sides of the emdash so you end up with:

    console.log( quotesArray[randomNumber].split(' — ') );
    

    NOTE: Remember that spaces inside the quotes are the ones that matter.

  12. Save the file and switch to index.html in Chrome (reload the page).

    Notice that now the two values are just text with no extra spaces.

  13. Return to index.html in your code editor.

  14. We want to add quotes to the testimonial (index 0), so add the following bold code:

    console.log( quotesArray[randomNumber].split(' — ')[0] );
    
  15. Save the file.

  16. Switch to index.html in Chrome and reload the page.

    Just the testimonial should show. Great! Now that we know our split is working, we can add it directly to our code.

  17. Return to index.html in your code editor.

  18. Select and copy .split(' — ')[0] from the console.log() line.

  19. Paste it in the line above, as shown here:

       document.getElementById('press-quote').textContent = quotesArray[randomNumber].split(' — ')[0];
       console.log( quotesArray[randomNumber].split(' — ')[0] );
    </script>
    
  20. We’re done testing, so add double slashes // to comment out the console.log():

    //console.log( quotesArray[randomNumber].split(' — ')[0] );
    

    NOTE: The Console is great for developers, but you should only use it during development. Once you’ve used it to test things, be sure to remove the code (or at least comment it out) so it does not execute on a live site.

  21. Save the file.
  22. Switch to index.html in Chrome and reload the page. Only the testimonial should be appearing on the page (it’s now missing the emdash and attribution).
  23. Return to your code editor.
  24. Let’s begin to add the quotation marks. After the equal sign, type two single quotes, and a plus (with spaces around it) as shown below in bold:

    document.getElementById('press-quote').textContent = '' + quotesArray[randomNumber].split(' — ')[0];
    
  25. Inside the single quotes, type an opening curly quote as follows:

    • Mac: Hit Opt–Left Bracket ([)
    • Windows: Hold Alt as you type 0147 (on the Keypad) and then release Alt. If it doesn’t work, hit the Num Lock key and try again.
    document.getElementById('press-quote').textContent = '' + quotesArray[randomNumber].split(' — ')[0];
    
  26. Save the file.

  27. Switch to index.html in Chrome and reload the page. You should see an opening quote () at the start of the testimonial on the page.
  28. Return to your code editor.
  29. Now let’s add the closing quote. After the .split(' — ')[0] type a plus (with spaces around it), and two single quotes as shown below in bold:

    document.getElementById('press-quote').textContent = '“' + quotesArray[randomNumber].split(' — ')[0] + '';
    
  30. Inside the single quotes, add an closing curly quote as follows:

    • Mac: Hit Opt–Shift–[ (that’s left square bracket)
    • Windows: Hold Alt as you type 0148 (on the Keypad) and then release Alt.
    document.getElementById('press-quote').textContent = '“' + quotesArray[randomNumber].split(' — ')[0] + '';
    
  31. Save the file.
  32. Switch to index.html in Chrome and reload the page.

    You should now have quotation marks to the start and end of the testimonial! We’re still missing the attribution, so let’s add it back in.

  33. Return to your code editor.
  34. To add the attribution (index 1), add the the bold code as shown below. Don’t miss adding the + before the new code you’re typing. (Feel free to copy and paste the first split and change 0 to 1.)

    document.getElementById('press-quote').textContent = '“' + quotesArray[randomNumber].split(' — ')[0] + '”' + quotesArray[randomNumber].split(' — ')[1];
    
  35. Finally, we must add the emdash back in. As shown below, after the closing quote () type an emdash with spaces around it. To type an emdash, use the following keystrokes:

    • Mac: Hit Shift–Opt–Hyphen (-)
    • Windows: Hold Alt as you type 0151 (on the Keypad) and then release Alt.
    document.getElementById('press-quote').textContent = '“' + quotesArray[randomNumber].split(' — ')[0] + '”  ' + quotesArray[randomNumber].split(' — ')[1];
    
  36. Save the file.
  37. Switch to index.html in Chrome and reload the page a few times. The testimonial should have quotes around it and the emdash and attribution should be back.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Random-Testimonial.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram