Skip to main content
March 23, 2026Dan Rodney/11 min read

Arrays, Math Object, & Displaying a Random Testimonial

Master JavaScript Arrays and Random Data Selection

Core JavaScript Concepts Covered

Arrays

Learn to create, edit, and manipulate JavaScript arrays. Understand zero-indexing and array methods like push() and sort().

Math Object

Explore mathematical operations and random number generation using JavaScript's built-in Math object and its methods.

DOM Manipulation

Practice selecting and modifying HTML elements using getElementById() and innerHTML properties for dynamic content.

Topics Covered in This JavaScript Tutorial:

Creating and manipulating arrays, leveraging the Math object for random number generation, implementing dynamic content selection, and building interactive user experiences

Exercise Preview

ex prev random testimonial

Exercise Overview

In this hands-on exercise, you'll master JavaScript arrays—one of the most fundamental data structures in programming. You'll discover how to create, modify, and dynamically access array elements, while learning to harness the Math object's powerful methods for generating random numbers. By combining these concepts, you'll build a dynamic testimonial rotator that enhances user engagement by displaying different content on each page load—a technique widely used in modern web applications for social proof, featured content, and A/B testing scenarios.

Getting Started

  1. 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).
  2. In your code editor, open index.html from the Random-Testimonial folder.
  3. Preview index.html in Chrome. (We'll be using its DevTools throughout this exercise.)
  4. 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, creating a more dynamic user experience. To accomplish this, we'll use an array—think of it as a sophisticated list structure that can store multiple values in a single variable. Arrays are ordered collections where each item is assigned a numerical index for easy access. Here's a crucial detail that trips up many developers: while humans typically start counting at 1, JavaScript arrays are zero-indexed, meaning the first item is at position 0, the second at position 1, and so forth. This indexing system is consistent across most programming languages and becomes second nature with practice.

Development Environment Setup

This exercise uses the Random-Testimonial folder with Visual Studio Code and Chrome DevTools. Having a proper code editor and browser debugging tools is essential for JavaScript development.

Creating an Array

Before diving into our testimonial rotator, let's explore array fundamentals using Chrome's Developer Console—an invaluable tool for testing JavaScript concepts in real-time.

  1. To open Chrome's Console, hit Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows). This opens Chrome DevTools, which remains one of the most powerful debugging environments available to web developers.

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

    let myArray = []

    NOTE: The [] square brackets denote an array literal in JavaScript—the most common and efficient way to create arrays.

  3. Currently our array is empty, which isn't very useful. Let's populate it with some values by adding the following bold code:

    let myArray = ['Madrid', 'Paris', 'London']
  4. Hit Return (Mac) or Enter (Windows) to execute the statement.
  5. The Console will display undefined, which is completely normal and expected behavior.

    NOTE: Why does it say undefined? In JavaScript, every statement returns a value. Variable declarations like let myArray = [] don't return meaningful values, so JavaScript returns undefined. This doesn't indicate an error—it simply means no value was returned. You'll see this behavior frequently when executing statements that perform actions rather than calculations.

  6. Type myArray and hit Return (Mac) or Enter (Windows) to inspect your array.
  7. You should see ['Madrid', 'Paris', 'London'] printed in the Console, confirming your array was created successfully.
  8. To access specific values from this array, you use bracket notation with the index number. Type:

    myArray[0]

    Remember: arrays are zero-indexed, so the first element is always at position 0. This indexing convention allows for more efficient memory management and mathematical operations.

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

  10. To access the third value (index position 2), type:

    myArray[2]

    TIP: Use your Up Arrow key to cycle through previous Console commands—a huge time-saver during development.

  11. Hit Return (Mac) or Enter (Windows) and the string 'London' will display.

Array Creation Process

1

Open Chrome Console

Use Cmd-Opt-J (Mac) or CTRL-Shift-J (Windows) to access the JavaScript console for testing

2

Declare Empty Array

Use let myArray = [] to create an empty array using square bracket notation

3

Add Array Values

Populate with strings like 'Madrid', 'Paris', 'London' separated by commas

4

Access Array Elements

Use zero-based indexing like myArray[0] to access the first element

Zero-Indexing in JavaScript

Remember that JavaScript arrays start counting from 0, not 1. So the first element is at index 0, the second at index 1, and so on.

DOM Element Selection

Use document.getElementById('press-quote') to select HTML elements, then access innerHTML property to read or modify the text content inside the element.

Editing an Array

Arrays in JavaScript are mutable, meaning you can modify their contents after creation. This flexibility makes them ideal for dynamic applications where data changes frequently.

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

    myArray[2] = 'Beijing'
  2. Hit Return (Mac) or Enter (Windows) and 'Beijing' will print, confirming the assignment.

  3. Arrays come with numerous built-in methods that provide powerful functionality. Let's explore these methods by typing:

    console.dir(myArray)

    NOTE: console.dir() displays an interactive, expandable view of an object's properties and methods. It's more detailed than console.log() and invaluable for understanding JavaScript objects' capabilities.

  4. Hit Return (Mac) or Enter (Windows) to execute the command.

  5. Click the arrow to the left of Array(3) to expand the array's details.

    • Notice the length property shows 3, indicating how many elements the array contains. This property is automatically maintained and extremely useful for dynamic operations.

    • Click the arrow next to [[Prototype]]: Array(0) to reveal available methods.

      You'll see an extensive list of built-in methods like push, pop, sort, filter, and map. These methods form the foundation of array manipulation in modern JavaScript development. Let's experiment with a few essential ones.

  6. To add a new value to the end of an array, use the push() method:

    myArray.push('New York')

    NOTE: The push() method modifies the original array and returns the new length. You can add multiple items at once by separating them with commas: myArray.push('Tokyo', 'Sydney').

  7. Hit Return (Mac) or Enter (Windows). The method returns 4, showing the array's new length.

  8. Type myArray and hit Return (Mac) or Enter (Windows) to view the updated array:

    ['Madrid', 'Paris', 'Beijing', 'New York']
  9. The length property is crucial for writing flexible, maintainable code. Test it by typing:

    myArray.length
  10. Hit Return (Mac) or Enter (Windows) and 4 will display, confirming our array now contains four elements.

  11. Arrays can be sorted alphabetically using the built-in sort() method. Type:

    myArray.sort()
  12. Hit Return (Mac) or Enter (Windows) and the Console displays the cities in alphabetical order:

    ['Beijing', 'Madrid', 'New York', 'Paris']

    NOTE: The sort() method modifies the original array. For more complex sorting (numbers, objects, custom criteria), you can pass a comparison function as an argument.

  13. Keep index.html open in Chrome—we'll return to test our testimonial rotator shortly.

Essential Array Methods

push() Method

Adds new elements to the end of an array. Returns the new length of the array after adding elements.

length Property

Returns the number of elements in an array. Useful for dynamic operations and loop conditions.

sort() Method

Arranges array elements in alphabetical order by default. Can be customized with comparison functions.

Creating an Array of Testimonials

Now that you understand array fundamentals, let's implement our dynamic testimonial system. We'll replace the static testimonial with an array of press quotes that displays randomly on each page load.

  1. Switch back to index.html in your code editor.
  2. Add a new script block before the closing </body> tag:

    </footer>
       <script>
          let quotes = [];
       </script>
    </body>
  3. Inside the [] brackets, add placeholder quotes using the following structure:

    <script>
       let quotes = [
          'first quote', 
          'second quote', 
          'third quote'
       ];
    </script>

    NOTE: Since our values are strings, each quote must be wrapped in single quotes. Each element is separated by a comma, but there's no comma after the final element—a common source of syntax errors for beginners.

  4. Save the file and reload the page in Chrome.
  5. Open the Console if it's not already visible.
  6. Type quotes and hit Return (Mac) or Enter (Windows) to verify your array was created successfully.
  7. Now we need to understand how to dynamically update the testimonial content. Return to your code editor.
  8. Around line 34, locate the testimonial p tag with the ID press-quote. This ID serves as our hook for JavaScript manipulation.
  9. Let's test our ability to modify this element using the Console. Switch back to Chrome.
  10. In the Console, access the testimonial element using:

    document.getElementById('press-quote')
  11. Hit Return (Mac) or Enter (Windows). The Console displays the complete HTML element, including all attributes and content.
  12. To access just the text content inside the element, we need the innerHTML property. Hit your Up Arrow key to reload the previous command.
  13. Append .innerHTML to the end:

    document.getElementById('press-quote').innerHTML
  14. Hit Return (Mac) or Enter (Windows) to execute.
  15. The Console displays the text content:

    "NAPS is by far the most significant cultural force of the decade.—New York Times"
  16. Now let's modify this text dynamically. Hit your Up Arrow key to reload the previous command.
  17. Add the assignment operator and array access at the end:

    document.getElementById('press-quote').innerHTML = quotes[2]

    NOTE: We're assigning the third quote (index 2) to replace the current testimonial text. Remember that array indexing starts at 0!

  18. Hit Return (Mac) or Enter (Windows) and watch the testimonial on the page change to third quote!

    This demonstrates the power of DOM manipulation—we can dynamically update any page content using JavaScript. Next, we'll implement randomization to automatically select different testimonials.

Array Creation Process

1

Open Chrome Console

Use Cmd-Opt-J (Mac) or CTRL-Shift-J (Windows) to access the JavaScript console for testing

2

Declare Empty Array

Use let myArray = [] to create an empty array using square bracket notation

3

Add Array Values

Populate with strings like 'Madrid', 'Paris', 'London' separated by commas

4

Access Array Elements

Use zero-based indexing like myArray[0] to access the first element

Zero-Indexing in JavaScript

Remember that JavaScript arrays start counting from 0, not 1. So the first element is at index 0, the second at index 1, and so on.

DOM Element Selection

Use document.getElementById('press-quote') to select HTML elements, then access innerHTML property to read or modify the text content inside the element.

The Math Object

JavaScript's Math object provides a comprehensive collection of mathematical constants and methods. For our testimonial rotator, we'll leverage its random number generation capabilities—a fundamental technique used in everything from games to A/B testing frameworks.

  1. In the Console, type Math and hit Return (Mac) or Enter (Windows) to explore this built-in object.

  2. Click the arrow next to Math to expand and examine its properties and methods.

    You'll see mathematical constants like PI and E (written in UPPERCASE by convention), plus methods for complex operations like sin, cos, floor, ceil, and random. These methods handle calculations that would be tedious to implement manually.

  3. The random() method generates pseudorandom numbers—perfect for our use case. Type:

    Math.random()
  4. Hit Return (Mac) or Enter (Windows). You'll see a random decimal number between 0 (inclusive) and 1 (exclusive).

  5. Hit the Up Arrow key and execute Math.random() again.
  6. Hit Return (Mac) or Enter (Windows) to confirm it generates different numbers each time.

    The key insight: we can scale this 0-1 range to match our array's index range. For example, if our array has 5 elements (indices 0-4), we multiply Math.random() by 5 to get numbers between 0-4.999, then round down to get clean integers.

  7. To demonstrate scaling, type:

    Math.random() * 4

    NOTE: Multiplying by 4 transforms our 0-1 range into 0-4, giving us five possible outcomes (0, 1, 2, 3, 4) when rounded down.

  8. Hit Return (Mac) or Enter (Windows) to see a random decimal between 0 and 4.

    Since array indices must be integers, we need to convert these decimals to whole numbers using rounding methods.

  9. The Math.floor() method rounds down to the nearest integer. Test it:

    Math.floor(3.78)
  10. Hit Return (Mac) or Enter (Windows) and it returns 3.

  11. The Math.ceil() method rounds up to the nearest integer. Test it:

    Math.ceil(3.78)
  12. Hit Return (Mac) or Enter (Windows) and it returns 4.

    For array indices, Math.floor() is typically preferred because it ensures we never exceed the valid index range. Using Math.ceil() could potentially generate an index that doesn't exist in our array.

Key Math Object Methods

Math.random()

Generates a random decimal number between 0 and 1. Forms the foundation for creating random selections.

Math.floor()

Rounds down to the nearest integer. Essential for converting decimal random numbers to array indices.

Math.ceil()

Rounds up to the nearest integer. Useful when you need to round up instead of down.

Random Selection Implementation

1

Generate Random Range

Use Math.random() * quotes.length to create a random number within array bounds

2

Convert to Integer

Wrap with Math.floor() to get whole numbers suitable for array indexing

3

Store in Variable

Assign result to randomNum variable for easier reference and code readability

4

Update DOM Element

Use document.getElementById() and innerHTML to replace testimonial with random selection

Dynamic Array Length Usage

Using quotes.length instead of hardcoding array size makes your code more maintainable. If you add or remove testimonials, the random selection automatically adjusts.

Graceful Fallback Strategy

Keep the static HTML testimonial as a fallback for users with JavaScript disabled and for SEO purposes. This ensures your content remains accessible regardless of browser settings.

Using the Math Object to Pick Random Testimonials

Let's combine our Math object knowledge with array manipulation to create a robust random testimonial selector that adapts automatically to any number of quotes.

  1. Switch back to your code editor to implement the production version.
  2. First, let's replace our placeholder quotes with real press testimonials. Navigate to the snippets folder and open press-quotes.txt.
  3. Select and copy all the text from this file.
  4. Close the file and return to index.html.
  5. Select the three placeholder quotes in your array.
  6. Replace them by pasting the real testimonials over the selected text.
  7. Save the file and reload the page in Chrome to ensure no syntax errors occurred.
  8. In the Console, test our dynamic random number generation. Type the following (don't execute yet):

    Math.random() * quotes.length

    This approach is superior to hard-coding a number because it automatically adapts when you add or remove testimonials. The quotes.length property always returns the current array size, making your code maintainable and flexible.

  9. To convert the decimal result to a valid array index, wrap the expression in Math.floor():

    Math.floor( Math.random() * quotes.length)
  10. Hit Return (Mac) or Enter (Windows). You should see a random integer between 0 and 4 (assuming you have 5 testimonials).
  11. Hit the Up Arrow key and execute again to verify you get different random integers.
  12. Perfect! Now let's integrate this logic into our webpage. Copy the complete expression:

    Math.floor(Math.random() * quotes.length)
  13. In your code editor, add this line after the quotes array:

    ];
       Math.floor(Math.random() * quotes.length);
    </script>
  14. To make this value reusable, store it in a descriptive variable:

    ];
       let randomNum = Math.floor(Math.random() * quotes.length);
    </script>
  15. Finally, implement the DOM manipulation to display the random testimonial:

    let randomNum = Math.floor(Math.random() * quotes.length);
       document.getElementById('press-quote').innerHTML = quotes[randomNum];
    </script>
  16. Save the file and reload the page in Chrome.

    Your page now displays a randomly selected testimonial from your array. This creates a more engaging user experience and helps showcase different aspects of your content.

  17. Reload the page several times to observe different testimonials appearing randomly.

    NOTE: We intentionally leave the static HTML testimonial in place as a graceful fallback for users with JavaScript disabled and to provide content for SEO crawlers that might not execute JavaScript. This progressive enhancement approach ensures accessibility and search engine optimization while delivering enhanced functionality to modern browsers.

Key Math Object Methods

Math.random()

Generates a random decimal number between 0 and 1. Forms the foundation for creating random selections.

Math.floor()

Rounds down to the nearest integer. Essential for converting decimal random numbers to array indices.

Math.ceil()

Rounds up to the nearest integer. Useful when you need to round up instead of down.

Random Selection Implementation

1

Generate Random Range

Use Math.random() * quotes.length to create a random number within array bounds

2

Convert to Integer

Wrap with Math.floor() to get whole numbers suitable for array indexing

3

Store in Variable

Assign result to randomNum variable for easier reference and code readability

4

Update DOM Element

Use document.getElementById() and innerHTML to replace testimonial with random selection

Dynamic Array Length Usage

Using quotes.length instead of hardcoding array size makes your code more maintainable. If you add or remove testimonials, the random selection automatically adjusts.

Graceful Fallback Strategy

Keep the static HTML testimonial as a fallback for users with JavaScript disabled and for SEO purposes. This ensures your content remains accessible regardless of browser settings.

Key Takeaways

1JavaScript arrays use zero-based indexing, meaning the first element is at position 0, not 1
2The Math.random() method generates decimal numbers between 0 and 1, which must be scaled and rounded for practical use
3Array methods like push(), sort(), and the length property provide powerful ways to manipulate and query array data
4Math.floor() combined with Math.random() creates random integers suitable for array index selection
5Dynamic array length usage with quotes.length makes code more maintainable than hardcoded values
6DOM manipulation through getElementById() and innerHTML allows JavaScript to update page content dynamically
7Chrome Developer Tools Console provides an interactive environment for testing JavaScript code before implementation
8Maintaining static HTML content as fallback ensures accessibility for users with JavaScript disabled

RELATED ARTICLES