JavaScript’s built-in objects provide a powerful set of tools that can greatly enhance your programming capabilities. These objects offer a wide range of functionalities, from manipulating data structures to performing mathematical calculations and handling dates and times. Understanding these built-in objects is essential for writing efficient and effective JavaScript code. In this article, we’ll explore the most commonly used JavaScript built-in objects, with detailed explanations and examples to help you make the most of them.
Object
The Object is the fundamental entity in JavaScript. It allows you to store collections of data and more complex entities.
Example:
let person = { firstName: 'John', lastName: 'Doe', age: 30, greet: function() { return `Hello, my name is ${this.firstName} ${this.lastName}`; } }; console.log(person.greet()); // Output: Hello, my name is John Doe
In this example, the person object has properties (firstName, lastName, age) and a method (greet). The greet method uses this to refer to the properties of the object.
Array
The Array object is used to store multiple values in a single variable. It provides a variety of methods to manipulate arrays.
Example:
let fruits = ['Apple', 'Banana', 'Cherry']; fruits.push('Date'); console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry', 'Date'] let firstFruit = fruits.shift(); console.log(firstFruit); // Output: Apple console.log(fruits); // Output: ['Banana', 'Cherry', 'Date']
Here, we create an array of fruits, add a new fruit using push, and remove the first fruit using shift. The push method adds an element to the end of the array, while shift removes the first element.
String
The String object allows you to work with textual data. It provides various methods for string manipulation.
Example:
let greeting = 'Hello, World!'; console.log(greeting.toUpperCase()); // Output: HELLO, WORLD! console.log(greeting.includes('World')); // Output: true console.log(greeting.slice(0, 5)); // Output: Hello
In this example, toUpperCase converts the string to uppercase, includes checks if the substring ‘World’ is present, and slice extracts a part of the string from index 0 to 5.
Number
The Number object allows you to work with numerical values and provides methods for number manipulation.
Example:
let num = 123.456; console.log(num.toFixed(2)); // Output: 123.46 console.log(Number.isInteger(num)); // Output: false let parsedInt = Number.parseInt('42'); console.log(parsedInt); // Output: 42
The toFixed method formats the number to a specified number of decimal places, isInteger checks if the value is an integer, and parseInt converts a string to an integer.
Math
The Math object provides mathematical constants and functions.
Example:
console.log(Math.PI); // Output: 3.141592653589793 console.log(Math.max(10, 20, 30)); // Output: 30 console.log(Math.random()); // Output: (a random number between 0 and 1)
Math.PI returns the value of π, Math.max returns the largest of the given numbers, and Math.random generates a random number between 0 and 1.
Date
The Date object is used for handling dates and times.
Example:
let now = new Date(); console.log(now.toISOString()); // Output: (current date and time in ISO format) let specificDate = new Date('2024-01-01'); console.log(specificDate.getFullYear()); // Output: 2024
In this example, new Date() creates a new date object with the current date and time, toISOString converts it to ISO format, and getFullYear extracts the year from a specific date.
RegExp
The RegExp object is used for pattern matching in strings.
Example:
let pattern = /hello/i; let str = 'Hello, World!'; console.log(pattern.test(str)); // Output: true let matches = str.match(pattern); console.log(matches[0]); // Output: Hello
In this example, /hello/i is a regular expression pattern that matches ‘hello’ in a case-insensitive manner. test checks if the pattern exists in the string, and match returns the matching results.
JSON
The JSON object is used for parsing and stringifying JSON data.
Example:
let jsonString = '{"name":"John", "age":30}'; let jsonObj = JSON.parse(jsonString); console.log(jsonObj.name); // Output: John let newJsonString = JSON.stringify(jsonObj); console.log(newJsonString); // Output: {"name":"John","age":30}
JSON.parse converts a JSON string into a JavaScript object, and JSON.stringify converts a JavaScript object into a JSON string.
Understanding and utilizing JavaScript’s built-in objects is crucial for writing efficient and effective code. These objects provide a wide array of methods and properties that simplify data manipulation, mathematical calculations, date handling, pattern matching, and more. By mastering these built-in objects, you can enhance your coding skills and create more robust and maintainable applications.
A Comprehensive Guide to JavaScript’s Built-In Objects was originally published in CarlosRojasDev on Medium, where people are continuing the conversation by highlighting and responding to this story.