JavaScript Built-in Objects (part 1)
JavaScript has several built-in objects that provide functionality to perform various tasks - they are essential to the language and can be used to make development easier and faster.
Here are some of the most commonly used built-in objects in JavaScript:
1. Object
The Object object is the base object for all JavaScript objects and provides generic methods for creating and manipulating objects:
// Create an object using the Object constructor
var person = new Object();
// Add properties to the object
person.name = "Charlie";
person.location = "Rome";
// Access the properties using dot notation
console.log(person.name); // prints: "Charlie"
console.log(person.location); // prints: "Rome"
// Use the Object.keys() method to get an array of property names
var propertyNames = Object.keys(person);
console.log(propertyNames); // prints: ["name", "location"]
// Use the Object.values() method to get an array of property values
var propertyValues = Object.values(person);
console.log(propertyValues); // Output: ["Charlie", "Rome"]
// Use the Object.entries() method to get an array of [key, value] pairs
var entries = Object.entries(person);
console.log(entries); // Output: [["name", "Charlie"], ["location", "Rome"]]
2. Array
The Array object is used to store multiple values in a single variable and provides methods for adding, removing, and manipulating elements.
const myArray = new Array('a', 42, 3.14);
For more, read our JavaScript Arrays article.
3. String
Represents and manipulates strings of text - here is how to create a string using the String constructor:
const firstName = new String("Charlie");
For more, read our JavaScript String Data Type article.
4. Number
Represents and manipulates numeric values, and provide utilitarian method, such as isNaN
(is Not a Number):
const theAnswer = new Number(42);
console.log(theAnswer); // prints: 42
console.log(Number.isNaN(theAnswer)); // prints: false
5. Boolean
The Boolean object is used to represent and manipulate Boolean (true/false) values.
const wasPublished = new Boolean(true);
console.log(wasPublished); // prints: "Boolean { true }"
console.log(wasPublished.valueOf()); // prints: true
6. Date
The Date object is used to represent and manipulate dates and times and also provides methods for getting and setting dates, formatting dates, etc:
var currentDate = new Date();
console.log(currentDate.getFullYear()); // prints: 2023
console.log(currentDate.getMonth()); // prints: 0 (January, as months are zero-indexed)
console.log(currentDate.getDate()); // prints: 16
console.log(currentDate.getDay()); // prints: 1
// days are also zero-indexed, with Sunday being 0
console.log(currentDate.getHours()); // prints: current hour in 24-hour format
console.log(currentDate.getMinutes()); // prints: current minute
console.log(currentDate.getSeconds()); // prints: current second
console.log(currentDate.getMilliseconds()); // prints: current millisecond
console.log(currentDate.getTime()); // prints: number of milliseconds since January 1, 1970
// parse a string into a Date object
var dateString = "2023-01-16T07:30:00.000Z";
var parsedDate = new Date(Date.parse(dateString));
console.log(parsedDate); // prints: "Date Mon Jan 16 2023 07:30:00 GMT+0000 (Greenwich Mean Time) ..."
7. Math
The Math object provides mathematical constants and functions, such as trigonometric functions, logarithms, and more:
// get the value of pi
var pi = Math.PI;
console.log(pi); // prints: 3.141592653589793
// round down to the nearest integer
var roundedDown = Math.floor(3.8);
console.log(roundedDown); // prints: 3
// round up to the nearest integer
var roundedUp = Math.ceil(3.2);
console.log(roundedUp); // prints: 4
// round to the nearest integer
var rounded = Math.round(3.5);
console.log(rounded); // prints: 4
// find the maximum value in a list of numbers
var max = Math.max(3, 5, 7, 2, 8);
console.log(max); // prints: 8
// find the minimum value in a list of numbers
var min = Math.min(3, 5, 7, 2, 8);
console.log(min); // prints: 2
// to generate a random number between 0 and 1
var random = Math.random();
console.log(random); // prints: a random number between 0 and 1
8. RegExp
The RegExp object is used to represent regular expressions, which are used to search for and replace text patterns.
// Create a regular expression to match phone numbers
// using the format XX-XXXX-XXXXXX
var phoneRegex = /^\d{2}-\d{4}-\d{6}$/;
// test if a string matches the regular expression
var phoneNumber = "44-7700-900123";
var isPhoneNumber = phoneRegex.test(phoneNumber);
console.log(isPhoneNumber); // prints: true
var invalidPhoneNumber = "123-456-789";
var isInvalidPhoneNumber = phoneRegex.test(invalidPhoneNumber);
console.log(isInvalidPhoneNumber); // prints: false
9. Function
The Function object is used to create functions in JavaScript - the syntax might look a little convoluted and unfamiliar:
const sum = new Function("a", "b", "return a + b;");
console.log(sum(2, 3)); // prints: 5
10. Error
The Error object is used to represent runtime errors in JavaScript and provides information about the error and a stack trace for debugging purposes.
var anError = new Error("Something went wrong");
The message
property contains the error message:
var anError = new Error("Something went wrong");
Here is an error generated by a division by zero:
try {
console.log(42/0);
} catch (error) {
console.log(error.message); // prints: "Infinity"
}
Errors can also be created and thrown where appropriate:
function divide(x, y) {
if (y === 0) {
throw new Error("Cannot divide by zero");
}
return x / y;
}
try {
console.log(divide(42, 0));
} catch (error) {
console.log(error.message); // prints: "Cannot divide by zero"
}
For more, see JavaScript Built-in Objects (part 2).