What Are Built-in Objects in JavaScript?

What Are Built-in Objects in JavaScript?

ยท

5 min read

Play this article

Built-in objects in JavaScript are predefined objects provided by the JavaScript runtime environment. These objects are available globally, meaning you can use them without the need for explicit declaration or instantiation. They serve as fundamental tools for handling various types of data and performing common operations. Let's dive into some of the essential built-in objects in JavaScript.

1. Object

The Object object is the most fundamental in JavaScript. It serves as the blueprint for creating user-defined objects and has properties and methods for object manipulation.

const person = {
  name: "John",
  age: 30,
};

2. Array

Arrays are used to store and manipulate collections of data. They provide methods for adding, removing, and iterating through elements.

// Joining elements of an array into a string
const fruits = ["apple", "banana", "cherry"];
const fruitString = fruits.join(", "); // Joins with a comma and space
console.log(fruitString); // Output: "apple, banana, cherry"

// Using array methods like map() to manipulate data
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

3. String

The String object is designed for working with text and strings of characters. It offers various methods for string manipulation.

Note: "String" is an object only when it is defined with a "new" keyword.

// Concatenating strings
const firstName = new string("John");
const lastName = new string("Doe");
const fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"

// Using string methods like indexOf() to find substrings
const text = "Hello, world!";
const indexOfWorld = text.indexOf("world");
console.log(indexOfWorld); // Output: 7 (index where "world" starts)

// Checking if a string starts with a specific prefix
const greeting = "Hello, there!";
const startsWithHello = greeting.startsWith("Hello");
console.log(startsWithHello); // Output: true

4. Number

The Number object handles numeric operations and provides methods for mathematical calculations.

Note: "Number" is an object only when it is defined with a "new" keyword.

// Creating a Number object
const num = new Number(42);

// Using Number properties and methods
console.log(num.toString()); // Output: "42"
console.log(num.toFixed(2)); // Output: "42.00"

// Converting a string to a number
const str = "123.45";
const parsedNumber = Number.parseFloat(str);
console.log(parsedNumber); // Output: 123.45

5. Boolean

The Boolean object represents true or false values and is often used in conditional statements.

Note: "Boolean" is an object only when it is defined with a "new" keyword.

// Creating a Boolean object
const bool = new Boolean(true);

// Using Boolean properties and methods
console.log(bool.toString()); // Output: "true"

// Checking the truthiness of values
const value1 = 5 > 3;
const value2 = 0;
console.log(Boolean(value1)); // Output: true
console.log(Boolean(value2)); // Output: false

6. Function

JavaScript functions are objects and can be used to define reusable blocks of code.

// Defining a function using a function expression
const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(3, 4)); // Output: 12

// Defining a function using a function declaration
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Output: "Hello, Alice!"

7. Date

The Date object is used for working with dates and times, allowing you to manipulate and format date values.

// Creating a date object
const today = new Date();
console.log(today); // Output: Current date and time

// Formatting a date as a string
const dateOptions = { year: "numeric", month: "long", day: "numeric" };
const formattedDate = today.toLocaleDateString("en-US", dateOptions);
console.log(formattedDate); // Output: "September 14, 2023"

8. Math

The Math object provides mathematical operations and constants, making complex calculations easier.

// Finding the square root
const number = 16;
const squareRoot = Math.sqrt(number);
console.log(squareRoot); // Output: 4

// Generating a random number between 1 and 10
const randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber); // Output: A random number between 1 and 10

9. RegExp (Regular Expression)

Regular expressions, represented by the RegExp object, are used for pattern matching within strings.

// Matching a regular expression pattern
const text = "Hello, World!";
const pattern = /hello/i; // Case-insensitive match for "hello"
const isMatch = pattern.test(text);
console.log(isMatch); // Output: true

// Extracting a portion of a string using a regular expression
const sentence = "The cat and the hat.";
const regex = /cat/g; // Global match for "cat"
const matches = sentence.match(regex);
console.log(matches); // Output: ["cat"]

10. Error

The Error object is employed in error handling, representing runtime errors that may occur during script execution.

// Throwing a custom error
function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed.");
  }
  return a / b;
}

try {
  const result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error(error.message); // Output: "Division by zero is not allowed."
}

11. JSON (JavaScript Object Notation)

JSON is a widely used data interchange format. JavaScript provides methods for parsing and stringifying JSON data.

// Parsing a JSON string to an object
const jsonString = '{"name": "John", "age": 30}';
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject.name); // Output: "John"

// Converting an object to a JSON string
const user = { name: "Alice", age: 25 };
const jsonUser = JSON.stringify(user);
console.log(jsonUser); // Output: '{"name":"Alice","age":25}'

12. Global Object

In web browsers, the global object is window, while in Node.js, it's global. It represents the global environment and contains global variables and functions.

console.log(window.innerHeight); // Browser-specific property
// Accessing global properties
console.log(globalThis); // Output: Global object (window in a browser, global in Node.js)

// Setting a global variable
globalThis.myGlobalVar = "Hello, Global!";
console.log(myGlobalVar); // Output: "Hello, Global!"

Working with Built-in Objects

To harness the power of built-in objects, you need to understand their properties and methods. JavaScript's extensive documentation and online resources provide detailed information about each object, helping you make the most of them in your projects.

Conclusion

In conclusion, built-in objects are the backbone of JavaScript, offering a rich set of tools to work with various data types and perform a wide range of operations. Mastery of these objects is key to becoming a proficient JavaScript developer. So, dive into the world of built-in objects, explore their capabilities, and enhance your coding skills. Happy coding!

Like this post if you find it helpful๐Ÿ˜Š . Follow me and subscribe to the newsletter to get notified of the latest posts on JavaScript and web development.

ย