Skip to main content
April 1, 2026Dan Rodney/12 min read

Introduction to Arrays & the Math Object

Master JavaScript Arrays and Math Objects Fundamentals

Core Concepts You'll Master

JavaScript Arrays

Learn to create, manipulate, and access array elements using zero-based indexing. Master essential array methods like push() and sort().

Math Object Methods

Discover random number generation and mathematical operations. Use Math.random() and Math.floor() for dynamic functionality.

Dynamic Content Display

Combine arrays with Math objects to create interactive web features that change content dynamically on page load.

Topics Covered in This JavaScript & jQuery Tutorial:

Creating and manipulating arrays, leveraging the Math object for randomization, implementing dynamic content selection from arrays

Exercise Preview

ex prev random testimonial

Exercise Overview

In this comprehensive exercise, you'll master one of JavaScript's most fundamental data structures: arrays. We'll explore how to create, populate, and manipulate arrays while integrating them with JavaScript's Math object to build dynamic, randomized content. By the end of this tutorial, you'll have created a sophisticated testimonial rotation system that demonstrates real-world application of these core programming concepts.

This exercise bridges the gap between static HTML content and dynamic, interactive web experiences—a critical skill for modern web development professionals.

Getting Started

  1. Open your code editor if it isn't already open.
  2. Close any files you may have open to maintain a clean workspace.
  3. For this exercise we'll be working with the Random-Testimonial folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. If your code editor supports project folders (like Visual Studio Code), open the entire folder to streamline file navigation.
  4. Open index.html from the Random-Testimonial folder.
  5. Preview index.html in Chrome—we'll be leveraging Chrome's powerful DevTools throughout this exercise.
  6. Notice the current testimonial: NAPS is by far the most significant cultural force of the decade. – New York Times.

    Our goal is to transform this static testimonial into a dynamic system using JavaScript that randomly displays different testimonials each time the page loads. To accomplish this, we'll implement an array—JavaScript's built-in data structure for storing ordered collections of values.

    Think of an array as a sophisticated filing cabinet where each drawer is numbered and can hold specific information. Arrays store multiple values in a single, organized structure, allowing you to access any specific value by referencing its position (index) within the collection. While humans typically count starting from 1, JavaScript arrays use zero-based indexing, meaning the first item is at position 0, the second at position 1, and so forth.

Setup Requirements

0/4

Creating an Array

Before diving into our testimonial system, let's establish a solid foundation by experimenting with arrays in Chrome's Console. This hands-on approach will give you immediate feedback and help solidify these concepts.

  1. We'll begin by exploring array fundamentals in the Console environment. Open Chrome's Console using Cmd–Opt–J (Mac) or CTRL–Shift–J (Windows).

  2. In the Console, type the following code but don't execute it yet:

    var myArray = [];

    The [] syntax is JavaScript's array literal notation—the standard way to create new arrays.

    Array Zero-Indexing Concept

    JavaScript arrays start counting from 0, not 1. This means the first item is at index 0, the second at index 1, and so on. This fundamental concept is crucial for accessing array elements correctly.

    Creating Your First Array

    1

    Open Chrome Console

    Press Cmd-Opt-J (Mac) or CTRL-Shift-J (Windows) to access the developer console

    2

    Declare Empty Array

    Type 'var myArray = [];' - the square brackets denote an empty array structure

    3

    Add Array Values

    Populate with strings: var myArray = ['Madrid', 'Paris', 'London']; separating each with commas

    4

    Test Array Access

    Use myArray[0]; to get 'Madrid', myArray[2]; to get 'London' - practice zero-based indexing

    Implementing Dynamic Testimonials

    1

    Create Script Section

    Add script tags before closing body tag and declare quotesArray with placeholder values

    2

    Target HTML Element

    Use document.getElementById('press-quote') to select the testimonial paragraph element

    3

    Modify Text Content

    Change testimonial text using .textContent property and array index access

TIP: Optimizing Your Console Experience

For better readability during this exercise, adjust your Console text size:

  • Mac: Cmd-Plus(+) to enlarge, Cmd-Minus(-) to reduce, Cmd-0 to reset
  • Windows: CTRL-Plus(+) to enlarge, CTRL-Minus(-) to reduce, CTRL-0 to reset
  • Now let's populate our array with actual data. Modify your code to include string values:

    var myArray = ['Madrid', 'Paris', 'London'];

    Notice how each string is wrapped in quotes and separated by commas—this is the proper syntax for array elements.

  • Execute the code by pressing Return (Mac) or Enter (Windows).
  • The Console displays undefined—this is completely normal and expected behavior.

    In JavaScript, operations either return a value or return undefined. Array creation is a statement that performs an action but doesn't produce a return value, hence the undefined response. This distinction between statements and expressions is fundamental to understanding JavaScript's execution model.

  • To inspect our newly created array, type myArray; and press Return (Mac) or Enter (Windows).
  • You should see ["Madrid", "Paris", "London"] displayed in the Console, confirming our array was created successfully.
  • To access specific array elements, we use bracket notation with the element's index position:

    myArray[0];

    Remember: JavaScript uses zero-based indexing, so the first element is always at position 0.

  • Execute this command to see "Madrid" returned.

  • To retrieve the third element, use index 2:

    myArray[2];

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

  • This returns "London", demonstrating how array indexing works in practice.

  • Editing an Array

    Arrays aren't just storage containers—they're dynamic data structures that can be modified after creation. Let's explore the most common array manipulation techniques.

    1. To modify an existing array element, use assignment with bracket notation:

      myArray[2] = 'Beijing';
    2. Execute this command—notice it returns "Beijing", confirming the assignment was successful.

    3. Arrays come with built-in methods that provide powerful functionality. Let's examine these methods using the console.dir() function:

      console.dir(myArray);

      The dir method creates an interactive directory-style listing of an object's properties and methods—essential for understanding what functionality is available.

    4. Execute this command to see the detailed array structure.

    5. Click the arrow next to Array[3] to expand the array's contents.

    6. Expand __proto__: Array[0] to reveal the complete list of available array methods. This prototype chain contains all the built-in functionality you can use with arrays.

    7. The push() method adds new elements to the end of an array:

      myArray.push('New York');

      You can add any value type to an array—strings, numbers, objects, or even other arrays.

    8. Execute this command—it returns 4, indicating the array now contains four elements.

    9. Verify the addition by typing myArray; and executing it. You should see:

      ["Madrid", "Paris", "Beijing", "New York"]
    10. The length property is crucial for dynamic programming—it tells you exactly how many elements an array contains:

      myArray.length;
    11. This returns 4, confirming our array's current size. The length property automatically updates as you add or remove elements.

    12. JavaScript arrays include a built-in sort() method for organizing data:

      myArray.sort();
    13. Execute this to see the cities arranged alphabetically:

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

      Note that sort() modifies the original array and returns the sorted result.

    14. Keep index.html open in Chrome—we'll return to it shortly to implement our testimonial system.

    Essential Array Methods

    push() Method

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

    length Property

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

    sort() Method

    Arranges array elements in alphabetical order. Modifies the original array structure.

    Console.dir() for Object Inspection

    Use console.dir(myArray) to see an interactive list of all available array methods and properties. This is invaluable for exploring what operations you can perform on your arrays.

    Creating an Array of Testimonials

    Now that you understand array fundamentals, let's apply this knowledge to build our dynamic testimonial system. This practical implementation will demonstrate how arrays solve real-world web development challenges.

    1. Return to index.html in your code editor.
    2. We'll add our JavaScript just before the closing </body> tag (around line 46) to ensure the DOM is fully loaded before our script executes:

      </footer>
      <script>
         var quotesArray = [];
      </script>
      </body>
    3. Populate the array with placeholder content to establish the structure:

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

      This multi-line format improves readability for arrays with multiple elements. Notice the comma after each element except the last—a trailing comma would cause syntax errors in older browsers.

    4. Save the file to preserve your changes.
    5. Switch to index.html in Chrome and refresh the page to load your new script.
    6. Open the Console if it's not already visible.
    7. Test your array by typing quotesArray; and executing it. You should see your placeholder quotes displayed.
    8. Now we need to understand how to dynamically update page content. Return to index.html in your code editor.
    9. Examine line 32—notice the testimonial paragraph has an ID attribute of press-quote. This ID provides the hook we need for JavaScript manipulation.
    10. Let's experiment with DOM manipulation in the Console. Switch back to Chrome.
    11. Access the testimonial element using the DOM API:

      document.getElementById('press-quote');
    12. Execute this command—it returns the complete HTML element object, showing you have successfully selected the target element.
    13. The element object contains many properties, but we specifically need to modify its text content.
    14. Use the Up Arrow to recall the previous command.
    15. Append .textContent to access just the text portion:

      document.getElementById('press-quote').textContent;
    16. Execute this to see the current testimonial text extracted cleanly.
    17. The textContent property should display:

      "NAPS is by far the most significant cultural force of the decade.—New York Times"
    18. Now let's modify this content. Recall the previous command with Up Arrow.
    19. Use assignment to replace the content with an array element:

      document.getElementById('press-quote').textContent = quotesArray[2];

      We're accessing the third element (index 2) from our quotes array. Remember that JavaScript arrays use zero-based indexing.

    20. Execute this command and watch the testimonial on the page instantly change to display third quote!

      This demonstrates the power of DOM manipulation—you can dynamically update any page content without requiring a page refresh. Now we need to make this selection random rather than hardcoded.

    Array Zero-Indexing Concept

    JavaScript arrays start counting from 0, not 1. This means the first item is at index 0, the second at index 1, and so on. This fundamental concept is crucial for accessing array elements correctly.

    Creating Your First Array

    1

    Open Chrome Console

    Press Cmd-Opt-J (Mac) or CTRL-Shift-J (Windows) to access the developer console

    2

    Declare Empty Array

    Type 'var myArray = [];' - the square brackets denote an empty array structure

    3

    Add Array Values

    Populate with strings: var myArray = ['Madrid', 'Paris', 'London']; separating each with commas

    4

    Test Array Access

    Use myArray[0]; to get 'Madrid', myArray[2]; to get 'London' - practice zero-based indexing

    Implementing Dynamic Testimonials

    1

    Create Script Section

    Add script tags before closing body tag and declare quotesArray with placeholder values

    2

    Target HTML Element

    Use document.getElementById('press-quote') to select the testimonial paragraph element

    3

    Modify Text Content

    Change testimonial text using .textContent property and array index access

    The Math Object

    JavaScript's built-in Math object provides a comprehensive suite of mathematical functions and constants. For our testimonial randomizer, we'll leverage its random number generation capabilities to create an unpredictable user experience.

    1. Let's explore the Math object's capabilities. In the Console, type Math; and execute it.

    2. Expand the Math object by clicking its arrow to reveal its extensive collection of properties and methods.

      You'll notice the object contains mathematical constants (written in UPPERCASE like PI) and numerous functions for calculations. For instance, Math.PI; provides the precise value of π for mathematical operations.

    3. The random() method is our key tool for generating unpredictability:

      Math.random();
    4. Execute this to see a random decimal number between 0 (inclusive) and 1 (exclusive).

    5. Use the Up Arrow to repeat the command and execute it again—notice you get a different random number each time.
    6. To make this useful for array indexing, we need to scale this decimal to match our array's length. For a five-element array, we'd want integers from 0 to 4:

      Math.random() * 4;

      This multiplication transforms our 0-1 range into a 0-4 range, but still returns decimal numbers.

    7. Execute this to see a random decimal between 0 and 4.

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

    8. The Math.floor() method rounds down to the nearest integer:

      Math.floor(3.78);
    9. This returns 3, demonstrating downward rounding.

    10. Conversely, Math.ceil() rounds up to the nearest integer:

      Math.ceil(3.78);
    11. This returns 4, showing upward rounding. For array indexing, we typically use Math.floor() to ensure we never exceed the array bounds.

    Math Object Constants vs Methods

    Math object contains constants like PI (uppercase) that never change, and methods like random() that perform calculations. Constants provide fixed mathematical values while methods execute operations.

    Math Rounding Methods

    FeatureMath.floor()Math.ceil()
    DirectionRounds DownRounds Up
    Example: 3.78Returns 3Returns 4
    Use CaseArray indicesCapacity planning
    Recommended: Use Math.floor() for array index generation to ensure valid integer indices
    Dynamic Array Length Benefits

    Using quotesArray.length instead of hard-coded numbers makes your code flexible. When you add or remove testimonials, the random selection automatically adjusts without code changes.

    Random Selection Implementation

    1

    Generate Random Decimal

    Math.random() produces a decimal between 0 and 1

    2

    Scale to Array Range

    Multiply by quotesArray.length to get range 0 to array size

    3

    Convert to Integer

    Wrap in Math.floor() to get whole number for valid array index

    4

    Apply to DOM

    Use result as array index to select random testimonial

    Using the Math Object to Pick Random Testimonials

    Now we'll combine our array knowledge with Math object functionality to create a robust random testimonial selector. This integration demonstrates how different JavaScript features work together to solve complex problems.

    1. Return to your code editor to implement the complete solution.
    2. We need realistic testimonial content. Navigate to the snippets folder and open press-quotes.txt—this file contains professionally crafted testimonials that will make our demo more compelling.
    3. Select and copy all the testimonial text from the file.
    4. Close the text file and return to index.html.
    5. Replace the placeholder quotes with the real testimonials by selecting the three temporary entries and pasting the new content.
    6. Save your changes to preserve the updated testimonials.
    7. Switch back to Chrome and refresh index.html to load the new data.
    8. In the Console, let's build our random selection formula step by step:

      Math.random() * quotesArray.length;

      Using quotesArray.length instead of a hardcoded number makes your code adaptive—it automatically adjusts if you add or remove testimonials later. This is a crucial principle of maintainable code.

    9. To convert this to a usable array index, wrap it with Math.floor():

      Math.floor( Math.random() * quotesArray.length);

      Pay careful attention to the parentheses placement—the entire multiplication must be completed before rounding.

    10. Execute this command to get a random integer within your array's valid index range.
    11. Press Up Arrow and execute again to verify you're getting different random numbers each time.
    12. Perfect! Copy this complete expression—we'll integrate it into our JavaScript:

      Math.floor(Math.random() * quotesArray.length);
    13. Switch back to index.html in your code editor.
    14. Add this expression to your script, creating a new line after the array declaration:

      ];
         Math.floor(Math.random() * quotesArray.length);
      </script>
    15. Store this random number in a variable for easy reference:

      ];
         var randomNumber = Math.floor(Math.random() * quotesArray.length);
      </script>
    16. Finally, implement the DOM update that replaces the static testimonial with our randomly selected one:

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

    18. Preview index.html in Chrome, refreshing if already open.

      Your page now displays a randomly selected testimonial each time it loads!

    19. Refresh the page several times to see different testimonials appear. You've successfully created a dynamic content system!

      Note: We're intentionally leaving the original —New York Times testimonial in the HTML as a fallback for users with disabled JavaScript and to maintain SEO value for search engines.

    Math Object Constants vs Methods

    Math object contains constants like PI (uppercase) that never change, and methods like random() that perform calculations. Constants provide fixed mathematical values while methods execute operations.

    Math Rounding Methods

    FeatureMath.floor()Math.ceil()
    DirectionRounds DownRounds Up
    Example: 3.78Returns 3Returns 4
    Use CaseArray indicesCapacity planning
    Recommended: Use Math.floor() for array index generation to ensure valid integer indices
    Dynamic Array Length Benefits

    Using quotesArray.length instead of hard-coded numbers makes your code flexible. When you add or remove testimonials, the random selection automatically adjusts without code changes.

    Random Selection Implementation

    1

    Generate Random Decimal

    Math.random() produces a decimal between 0 and 1

    2

    Scale to Array Range

    Multiply by quotesArray.length to get range 0 to array size

    3

    Convert to Integer

    Wrap in Math.floor() to get whole number for valid array index

    4

    Apply to DOM

    Use result as array index to select random testimonial

    Optional Bonus: Adding Quote Marks Around the Testimonial

    Let's enhance our testimonial system with a professional touch. Currently, each entry contains both the testimonial and its attribution separated by an em dash. We can use JavaScript's string manipulation capabilities to add proper quotation marks around just the testimonial portion, creating a more polished presentation.

    1. Return to index.html in your code editor to implement this enhancement.

    2. JavaScript's split() method can break a string into an array based on a specified delimiter. Let's experiment with this functionality by adding a test line to our script (around line 57):

      document.getElementById('press-quote').textContent = quotesArray[randomNumber];
         console.log( quotesArray[randomNumber].split('') );
      </script>
    3. Inside the split method's quotes, you need to enter an em dash (—) character:

      • Mac: Press Shift–Opt–Hyphen(-)
      • Windows: Hold ALT while typing 0151 on the numeric keypad, then release ALT. If this doesn't work, ensure Num Lock is enabled and try again.

      Your code should look like this:

      console.log( quotesArray[randomNumber].split('') );
    4. Save the file to apply this debugging code.
    5. Switch to index.html in Chrome and refresh the page.
    6. Open the Console to examine the split operation results.
    7. You'll see the testimonial has been split into a two-element array, similar to:

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

      Notice that the split() method has removed the em dash delimiter and created separate array elements.

    8. Click the arrow to expand this array and examine its structure.

      The array contains two elements: the testimonial (index 0) and the attribution (index 1). You'll also notice extra spaces that we need to handle properly.

    9. Return to index.html in your code editor to refine our approach.

    10. Modify the split delimiter to include spaces around the em dash for cleaner separation:

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

      This approach will eliminate the unwanted spaces in our resulting array elements.

    String Split() Method Power

    The split() method transforms a single string into an array by breaking it at specified characters. This enables precise text manipulation for formatting testimonials and attributions separately.

    Advanced Text Formatting

    1

    Identify Split Character

    Use emdash (—) to separate testimonial from attribution

    2

    Test Split Method

    Use console.log() to verify split() creates proper array structure

    3

    Extract Testimonial Only

    Access index [0] to get just the testimonial portion

    4

    Add Professional Quotes

    Concatenate curly quotes for polished presentation

    Key Takeaways

    1JavaScript arrays use zero-based indexing, starting from index 0 rather than 1, which is fundamental for proper element access
    2Arrays provide powerful methods like push(), sort(), and length property for dynamic data manipulation and organization
    3Math.random() generates decimal numbers between 0 and 1, requiring multiplication and Math.floor() for practical integer results
    4Combining Math.floor(Math.random() * array.length) creates random integer indices perfect for array element selection
    5Chrome DevTools Console serves as an essential testing environment for experimenting with JavaScript code before implementation
    6Document.getElementById() and textContent property enable dynamic HTML content modification through JavaScript
    7Using array.length instead of hard-coded numbers creates flexible, maintainable code that adapts to array size changes
    8String split() method transforms single strings into arrays, enabling precise text manipulation and formatting control

    RELATED ARTICLES