Back to JavaScript
2026-01-059 min read

Standard objects by category (JavaScript)

Learn Standard objects by category (JavaScript) step by step with clear examples and exercises.

Title: Standard Objects by Category (JavaScript)

Why This Matters

Understanding JavaScript's standard built-in objects is crucial for mastering the language, especially when it comes to web development. These objects provide essential functionalities that help you manipulate data structures, handle errors, and interact with the browser environment. A solid grasp of these objects can make your code more efficient, readable, and maintainable.

Importance of Standard Built-in Objects

  • Provide predefined objects for various tasks, saving you time and effort in creating custom solutions.
  • Offer consistent interfaces across different browsers and environments.
  • Help write cleaner, more concise code by providing reusable methods and properties.

Prerequisites

Before diving into standard built-in objects, it's important to have a good understanding of the following concepts:

  1. JavaScript syntax and variables
  2. Basic data structures like arrays and objects
  3. Control flow statements (if-else, switch, loops)
  4. Functions and function declarations
  5. Callbacks and event handling
  6. DOM manipulation using JavaScript
  7. Understanding the difference between primitive values and object values
  8. Familiarity with ES6 features like arrow functions, template literals, and destructuring assignments
  9. Basic understanding of prototypes and inheritance in JavaScript (optional but recommended)

Core Concept

JavaScript's standard built-in objects are a collection of predefined objects that come with the language. These objects provide various functionalities and can be accessed directly without needing to define them yourself. In this lesson, we will explore several categories of these objects:

  1. Global Object - The global object is the topmost object in JavaScript's hierarchy and represents the window or browser environment in a web context. It contains properties and methods related to the browser and document.

Global Object Properties

  • window (in browsers) or globalThis (in Node.js): provides access to the global scope and all its properties.
  • self: an alias for the global object in some environments like web workers.
  1. Math Object - This object provides various mathematical constants, functions, and properties for performing mathematical operations.

Math Object Methods

  • pow(base, exponent): raises a number to a power.
  • sqrt(number): calculates the square root of a number.
  • abs(number): returns the absolute value of a number.
  • min(...numbers) and max(...numbers): find the minimum or maximum value among a list of numbers, respectively.
  • random(): generates a random number between 0 (inclusive) and 1 (exclusive).
  1. Date Object - The Date object allows you to work with dates and times, including creating, formatting, and manipulating date objects.

Date Methods

  • getFullYear(), getMonth(), getDate(): retrieve the year, month, and day of a Date object, respectively.
  • setFullYear(), setMonth(), setDate(): set the year, month, and day of a Date object, respectively.
  • getTimezoneOffset(): returns the time difference between the date's local time and Coordinated Universal Time (UTC) in minutes.
  • toLocaleString(): formats the date and time according to the user's locale settings.
  • toString(): converts a Date object into a string representation of its date and time.
  1. String Object - The String object provides methods for manipulating strings, such as searching, replacing, and splitting.

String Methods

  • indexOf(substring), lastIndexOf(substring), includes(substring): search a string for a specific substring or character.
  • replace(searchValue, replacement): replace all occurrences of a specified value in a string with another value.
  • split(separator): divide a string into an array based on a specified separator.
  • trim(), padStart(length, padString), padEnd(length, padString): modify the whitespace around a string or add padding to meet a specific length.
  • charCodeAt(index): returns the Unicode value of a character at a specified index in a string.
  1. Number Object - This object provides properties and methods related to numbers, like converting between different number systems or rounding numbers.

Number Methods

  • toFixed(digits): rounds a number to a specified number of decimal places and returns it as a string.
  • toExponential(digits): returns the exponential representation of a number in the format [coefficient]e[exponent].
  • toString(base): converts a number to a string in a specified base (from 2 to 36).
  • parseFloat(string) and parseInt(string, base): convert a string to a floating-point number or integer, respectively.
  1. Array Object - Although not a built-in object, the Array constructor is an essential part of JavaScript's standard library. It allows you to create and manipulate arrays easily.

Array Methods

  • push(element), pop(): add an element to the end or remove the last element from an array, respectively.
  • shift(), unshift(element): remove the first element or add an element to the beginning of an array, respectively.
  • splice(index, howMany[, item1], ...[itemX]): insert, delete, or replace elements in an array at a specified index.
  • sort(): sort the elements of an array in ascending order (or descending order with a custom comparator function).
  • filter(callback), map(callback), reduce(callback[, initialValue]): perform operations on arrays and return new arrays based on the results.
  1. Error Objects - Error objects are used for handling exceptions and errors in your code. Examples include Error, RangeError, SyntaxError, and more.

Error Handling

  • Try-catch blocks: catch and handle errors that occur during execution.
  • window.onerror: handle unhandled JavaScript errors in the browser environment.

Worked Example

Let's take a look at an example that demonstrates using some of these built-in objects:

// Using the Math object to calculate square root and perform other mathematical operations
const number = 4;
console.log(Math.sqrt(number)); // Output: 2
console.log(Math.pow(2, 3)); // Output: 8
console.log(Math.random()); // Output: A random number between 0 and 1 (exclusive)

// Creating a new Date object for today and formatting it as a string using the `toLocaleString()` method
const today = new Date();
console.log(today.toLocaleString()); // Output: Current date and time

// Using the String object to find the index of a substring, replace all occurrences of a character, and convert a string to uppercase
const text = "Hello, world!";
console.log(text.indexOf("world")); // Output: 6
console.log(text.replace(/a/g, "@")); // Output: He@llo, @orld!
console.log(text.toUpperCase()); // Output: HELLO, WORLD!

// Creating an array containing the numbers 1 through 5 using the Array constructor and sorting it in ascending order
const myArray = new Array(5).fill().map((_, i) => i + 1);
console.log(myArray.sort()); // Output: [1, 2, 3, 4, 5]

// Using the Number object to convert a number to exponential notation and round a number to two decimal places
const bigNumber = 1_000_000;
console.log(bigNumber.toExponential()); // Output: 1e6
console.log((3.14159).toFixed(2)); // Output: "3.14"

// Using the Error object to create a custom error and handle it with a try-catch block
try {
throw new Error("Custom error message");
} catch (error) {
console.log(error.message); // Output: Custom error message
}

Common Mistakes

  1. Forgetting to call methods on objects - Always remember to call methods on their respective objects using the dot notation (e.g., Math.sqrt(), not just sqrt()).
  2. Ignoring the return values of methods - Some methods return values that you might need for further processing. Don't forget to assign these return values to variables when necessary.
  3. Not properly handling errors - Make sure to use try-catch blocks or appropriate error handling methods (e.g., try { ... } catch (error) { ... }, window.onerror) to handle potential errors in your code.
  4. Using the assignment operator (=) instead of the comparison operator (==) - This can lead to unexpected results when comparing values, especially with objects and primitive wrappers.
  5. Confusing primitive values and object values - Primitive values are simple data types like numbers, strings, booleans, null, and undefined. Objects are more complex data structures that can have properties and methods.
  6. Not understanding the difference between mutable and immutable objects - Some built-in objects (e.g., String) are immutable, meaning they cannot be modified once created. Always create new instances when you need to change their content.
  7. Not using strict mode - Strict mode helps prevent certain errors and unexpected behavior by disallowing certain features and enforcing stricter syntax rules. To enable strict mode, add "use strict" at the beginning of your JavaScript files or scripts.
  8. Overusing built-in objects - While built-in objects are powerful tools, overusing them can lead to code that is difficult to read and maintain. Consider creating custom functions when appropriate.
  9. Not taking advantage of ES6 features with built-in objects - Make sure to familiarize yourself with ES6 features like arrow functions, template literals, and destructuring assignments to write more concise and modern JavaScript code.

Practice Questions

  1. Write a JavaScript function that calculates the factorial of a given number using the Math object's exponential function.
  2. Create a Date object for the date of your next birthday and format it as a string using the toLocaleString() method.
  3. Write a script that finds all occurrences of the word "JavaScript" in a given string using the indexOf() or search() method.
  4. Convert the number 1024 from decimal to binary using the Math object's methods.
  5. Create an array containing the numbers 1 through 10 and sort it in ascending order using the Array object's sort() method.
  6. Write a function that checks if a given value is a number, and if so, round it to two decimal places using the Math object's methods.
  7. Create an Error object with a custom message and throw it in a try-catch block to handle the error gracefully.
  8. Use the String object's replace() method to replace all occurrences of the letter "a" with the letter "4" in a given string.
  9. Write a function that returns the number of vowels in a given string using the String object's methods.
  10. Use the Date object's methods to calculate the number of days remaining until your next birthday.

FAQ

Q: Why can't I access the Math object as a variable?

A: The Math object is not a regular JavaScript variable, but rather a built-in object that you call methods on. You cannot assign it to another variable or reassign its value.

Q: What happens if I don't catch an error in my code?

A: If an error occurs and no error handling mechanism is in place, the script will terminate, and any subsequent code will not be executed. Additionally, unhandled errors can cause unexpected behavior or crashes in your application.

Q: Can I create a custom object that extends built-in objects?

A: Yes, you can create custom objects that inherit properties and methods from existing built-in objects using the Object.create() method or by setting prototype chains. However, it's important to be aware of potential conflicts with existing properties and methods when doing so.

Q: How do I determine if a value is an object in JavaScript?

A: You can use the typeof operator to check if a value is an object. If the result is "object", then the value is indeed an object (either primitive wrapper or custom object). However, Note that that primitive values like numbers and strings will not be considered objects in this case.

Q: What are some best practices for working with built-in objects in JavaScript?

A: Some best practices include using descriptive variable names, following a consistent coding style, minimizing the use of global variables, and using strict mode to prevent errors. Additionally, it's important to understand the difference between primitive values and object values, as well as the differences between mutable and immutable objects.

Standard objects by category (JavaScript) | JavaScript | XQA Learn