Skip to Content
Lab 3

Built-in Objects and APIs

Overview and Objectives

In this lab, learners work with JavaScript’s built-in objects like Math, JSON, and RegExp to perform calculations, data serialization, and pattern matching. They also extend native object prototypes by adding custom methods to enhance their understanding of composite data types. By the end of this lab, learners will be able to:

  • Distinguish between primitive data types and objects (composite types) in JavaScript.
  • Utilize built-in global objects such as Math for mathematical operations.
  • Use the JSON object to serialize (stringify) and deserialize (parse) data.
  • Create and use RegExp (Regular Expression) objects to match patterns in strings.
  • Extend built-in object types by adding methods to their prototypes.
  • Gain familiarity with additional built-in types like Array and Date (as composite types) and their usage.

Tasks and Instructions

This lab consists of several independent tasks to practice different built-in objects and functions.

Task 1: Using the Math Object

  • Perform some calculations using JavaScript’s Math object.
    • Generate a random integer between 1 and 100 and log it. Hint: Use Math.random() to get a number between 0 and 1, multiply by 100, then use Math.floor() or Math.ceil() to round to an integer in the desired range.
    • Calculate the area of a circle with radius 5. Use Math.PI for π and the formula area = π * r^2. Use Math.pow() or the exponentiation operator to square the radius. Log the result (expected ~78.54).
    • Compute the maximum of a set of numbers using Math.max(). For example, given numbers 10, 47, 33, 5, log the maximum. Similarly, try Math.min() for the minimum of those numbers.
    • Output: For each of the above, use console.log to show the result (e.g., “Random number: X”, “Circle area: Y”, etc.).

Task 2: JSON Stringify and Parse

  • Practice converting data to and from JSON.
    • Create a JavaScript object (literal) representing a book with properties like title, author, and year (e.g., title: “JavaScript Guide”, author: “Coder”, year: 2021).
    • Convert this object into a JSON string using JSON.stringify(). Save the result in a variable and log it to verify it is a string in JSON format (e.g., looks like {"title":"JavaScript Guide","author":"Coder","year":2021}).
    • Now take the JSON string and convert it back into a JavaScript object using JSON.parse(). Store this in a new variable and log one of its properties (e.g., log the author or title) to confirm you successfully reconstructed the original object.
    • Note: Ensure that after parsing, the type of the result is an object (you can use typeof to check it logs “object”).

Task 3: Working with RegExp

  • Create and use regular expressions to find patterns in text.
    • Define a string variable containing a mix of letters and digits, for example: "Hello 123, this is JS Essentials 2!".
    • Create a RegExp (regular expression) that matches all sequences of digits in the string. You can do this by using the literal syntax /\d+/g (where \d means any digit and the + means one or more, and g is the global flag to find all occurrences). Alternatively, use the RegExp constructor: new RegExp("\\d+", "g").
    • Use the string’s .match() method with your regex to find all substrings that match (or use the regex’s .test() in a loop, but .match() is simpler here). The result should be an array of matched sequences of digits. Log the array of matches. For the example above, you should get something like ["123", "2"] (the “2” from “2!” separately, because there’s a space before it, splitting the sequences).
    • Next, create a regex to validate a simple pattern. For instance, check if a given string looks like a valid hex color code (e.g., #FF5733). A simple regex for this could be /^#[0-9A-Fa-f]{6}$/ (hash followed by exactly six hex digits). Test this regex on a couple of strings (one valid hex code like “#ABC123” and one invalid like “12345” or “#GGGGGG”). Use .test() to log true/false for each test string.
    • Note: Regular expressions are powerful; this step is just to get comfortable with using them in code. If the exact pattern is not obvious, focus on using .match or .test correctly rather than creating the perfect regex.

Task 4: Extending a Built-in Prototype

  • Add a custom method to a built-in object type.
    • For example, add a method reverse() to the String.prototype so that all string instances can use it. The method should return the string reversed. Hint: You can convert the string to an array of characters, reverse the array, and join it back into a string, or use a loop to build the reversed string.
      String.prototype.reverse = function() { return this.split("").reverse().join(""); };
      (The above single-liner works because inside the function, this is the string instance which is temporarily a String object, allowing .split etc.)
    • After defining this, test it on a couple of strings:
      console.log("Hello".reverse()); // Expected output: "olleH" console.log("JavaScript".reverse()); // "tpircSavaJ"
    • Next, try extending the Array prototype by adding a method last() that returns the last element of the array (i.e., this[this.length - 1]).
      Array.prototype.last = function() { return this.length > 0 ? this[this.length - 1] : undefined; };
    • Test the new Array last() method:
      const nums = [10, 20, 30]; console.log(nums.last()); // Expected output: 30 console.log([].last()); // Expected output: undefined (for empty array)
    • Important: Use these new methods in a few different examples to ensure they work for all strings/arrays. Be careful not to overly rely on extended prototypes in real-world code, but this exercise shows how JavaScript allows such extensions.

Submission Criteria

Via a GitHub repository, submit the following via Canvas:

  • Submit your code file lab3.js containing all tasks. You can keep the tasks separated by comments for clarity (e.g., // Task 1: Math, // Task 2: JSON, etc.). Make sure to include the test examples and console logs so the output of each task can be verified.
  • The code should run without errors in a Node or browser environment. Ensure that the extended prototype methods (for String and Array) do not conflict with existing methods (use unique names like the ones suggested).
  • Provide a brief comment or observation for each task’s output (for example, note what random number was generated, or the result of the regex test) to demonstrate you checked the results.

Grading Rubric

CriteriaPoints
Utilized Math object methods correctly (random number generation, rounding, calculations) and logged expected results.8 points
Converted an object to JSON string with JSON.stringify and back to an object with JSON.parse, with correct output verification.8 points
Created and used RegExp to find patterns (digit sequences) and tested regex on sample strings, logging correct matches and boolean results.8 points
Added custom method(s) to built-in prototypes (String, Array) and demonstrated their functionality with examples.8 points
Code quality and completeness: all tasks are attempted with no runtime errors; results of operations are clearly logged and labeled for review.8 points

Total Points: 50 points

Note

Partial credit will be given for each independent task. For example, even if the regex part is not fully correct, you can still earn points for successful Math and JSON tasks. Each bullet in the rubric corresponds to a task, so make sure to attempt all to maximize your score.