Essential JavaScript Built-in Constructors and Methods
Reference Type Constructors
Object Constructor
The Object constructor creates generic objects. Several useful static methods are available:
- Object.keys(object): Retrieves all enumerable property names (keys) from the object. Returns an array of strings.
- Object.values(object): Retrieves all enumerable property values from the object. Returns an array.
- Object.assign(target, ...sources): Copies enumerable properties from source objects to a target object. Commonly used for object cloning or property merging.
const original = { id: 1001, name: 'Alice' };
const duplicate = {};
// Copy properties
Object.assign(duplicate, original);
// Add new properties
Object.assign(original, { role: 'Developer' });
console.log(duplicate); // { id: 1001, name: 'Alice' }
console.log(original); // { id: 1001, name: 'Alice', role: 'Developer' }
Array Constructor
The Array constructor is used to create and work with arrays.
Core Array Instance Methods
These methods are fundamental for functional-style array operations.
| Method | Purpose | Key Points |
|---|---|---|
| forEach | Iterates over array elements. | Does not return a value. Ideal for executing side effects for each item. |
| filter | Creates a new array with elements that pass a test. | Returns a new array containing only the matching elements. |
| map | Creates a new array by transforming every element. | Returns a new array of the same length, with each element processed by the callback. |
| reduce | Accumulates a single result from the entire array. | Takes a reducer function and an optional initial accumulator value. |
Understanding reduce()
The reduce(callback, initialValue) method executes a "reducer" function on each element, passing the accumulated result forward.
- If
initialValueis provided, it serves as the first accumulator (prev). - If not, the first array element becomes the initial accumulator.
- The callback's return value becomes the
prevfor the next iteration.
const monthlyExpenses = [
{ category: 'Rent', amount: 1200 },
{ category: 'Utilities', amount: 250 },
{ category: 'Groceries', amount: 400 }
];
// Calculate total expenses
const totalCost = monthlyExpenses.reduce((accumulator, item) => {
return accumulator + item.amount;
}, 0);
console.log(totalCost); // 1850
Additional Array Instance Methods
Other practical methods for array manipulation.
| Method | Purpose |
|---|---|
| join(separator) | Joins all elements into a string, separated by separator. |
| find(callback) | Returns the value of the first element satisfying the callback test. Returns undefined if none match. |
| every(callback) | Tests if all elements pass the callback test. Returns a Boolean. |
| some(callback) | Tests if atleast one element passes the callback test. Returns a Boolean. |
| concat(array) | Merges two or more arrays, returning a new array. |
| sort(callback) | Sorts the array elements in place. |
| splice(start, deleteCount, ...items) | Changes array contents by removing/replacing elements and/or adding new ones in place. |
| reverse() | Reverses the order of elements in the array in place. |
| findIndex(callback) | Returns the index of the first element satisfying the callback test. Returns -1 if none match. |
Converting Array-like Objects
Use the static method Array.from(arrayLike) to convert array-like objects (e.g., arguments, NodeList) into true arrays.
const nodeList = document.querySelectorAll('div');
const divArray = Array.from(nodeList); // Now has access to array methods.
Primitive Wrapper Constructors
Primitive types like string, number, and boolean have corresponding constructor objects (String, Number, Boolean) that provide useful methods.
String Constructor
Common string instance methods include:
| Method | Purpose |
|---|---|
| split(separator) | Splits a string into an array of substrings based on a separator. |
| substring(startIndex [, endIndex]) | Extracts characters between two indices. The character at endIndex is not included. |
| startsWith(searchString [, position]) | Checks if the string begins with the specified characters. Returns Boolean. |
| includes(searchString [, position]) | Checks if the string contains the specified characters. Returns Boolean. |
| toUpperCase() | Returns a new string converted to uppercase. |
| toLowerCase() | Returns a new string converted to lowercase. |
| indexOf(searchValue) | Returns the index of the first occurrence of a specified value. Returns -1 if not found. |
| endsWith(searchString [, length]) | Checks if the string ends with the specified characters. Returns Boolean. |
| replace(searchValue, newValue) | Replaces part of the string. Supports regex for searchValue. |
| match(regexp) | Retrieves matches when matching a string against a regular expression. |
Number Constructor
The Number constructor provides methods for formatting numbers.
- toFixed(digits): Formats a number using fixed-point notation, rounding to a specified number of decimal places (
digits). Returns a string.
const measurement = 98.76543;
console.log(measurement.toFixed(1)); // "98.8"
console.log(measurement.toFixed(3)); // "98.765"