Learn Essential Javascript Methods and Objects
Updated: March 27, 2026
TL;DR
Master JavaScript's core methods—Array operations (map, filter, reduce, groupBy), String manipulation, Object utilities, Map/Set data structures, and Promise patterns—to write efficient, readable code across all project types.
JavaScript's standard library is extensive, and knowing which methods to reach for separates novice developers from professionals. This reference guide organizes essential methods by category with practical examples and TypeScript type signatures. Whether you're processing data, manipulating strings, or orchestrating async operations, these patterns will become muscle memory.
Array Methods
Iteration and Transformation
const numbers = [1, 2, 3, 4, 5];
// map: transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: keep elements that match a condition
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce: aggregate to a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// forEach: execute side effects (no return value)
numbers.forEach((n, index) => {
console.log(`Index ${index}: ${n}`);
});
TypeScript Signatures:
// map<U>(callback: (value: T, index: number, array: T[]) => U): U[]
const squared: number[] = numbers.map(n => n * n);
// filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S): S[]
const filtered: number[] = numbers.filter(n => n > 2);
// reduce<U>(callback: (prev: U, curr: T, index: number, array: T[]) => U, init: U): U
const total: number = numbers.reduce((sum, n) => sum + n, 0);
Finding Elements
const users = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
{ id: 3, name: 'Charlie', role: 'user' }
];
// find: return first matching element
const admin = users.find(u => u.role === 'admin');
console.log(admin); // { id: 1, name: 'Alice', role: 'admin' }
// findIndex: return index of first match
const idx = users.findIndex(u => u.id === 2);
console.log(idx); // 1
// includes: check if value exists
const hasZero = [1, 2, 3].includes(0);
console.log(hasZero); // false
// some: test if at least one element matches
const hasAdmin = users.some(u => u.role === 'admin');
console.log(hasAdmin); // true
// every: test if all elements match
const allActive = users.every(u => u.active !== false);
console.log(allActive); // true (if no explicit false values)
Grouping and Aggregation (ES2024)
const transactions = [
{ id: 1, type: 'income', amount: 100 },
{ id: 2, type: 'expense', amount: 50 },
{ id: 3, type: 'income', amount: 200 },
{ id: 4, type: 'expense', amount: 30 }
];
// Array.groupBy: group by key function
const byType = Array.groupBy(transactions, t => t.type);
console.log(byType.income); // [{ id: 1, ... }, { id: 3, ... }]
// Combining groupBy with reduce
const totals = Object.entries(
Array.groupBy(transactions, t => t.type)
).reduce((acc, [type, items]) => {
acc[type] = items.reduce((sum, t) => sum + t.amount, 0);
return acc;
}, {});
console.log(totals); // { income: 300, expense: 80 }
Flattening and Joining
// flat: flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] — flattens one level
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] — flattens two levels
// flatMap: map and flatten in one pass
const sentences = ['Hello world', 'Nice day'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['Hello', 'world', 'Nice', 'day']
// join: combine array elements into string
const csv = ['Alice', 'Bob', 'Charlie'].join(', ');
console.log(csv); // 'Alice, Bob, Charlie'
String Methods
Searching and Checking
const text = 'Hello, JavaScript!';
// includes: check if substring exists
console.log(text.includes('Java')); // true
// startsWith / endsWith: check string boundaries
console.log(text.startsWith('Hello')); // true
console.log(text.endsWith('!')); // true
// indexOf / lastIndexOf: find position
console.log(text.indexOf('o')); // 4
console.log(text.lastIndexOf('o')); // 14
// search: find with regex
console.log(text.search(/script/i)); // 7 — case insensitive
// match: find all matches with regex
const matches = 'abc123def456'.match(/\d+/g);
console.log(matches); // ['123', '456']
Transformation
// toUpperCase / toLowerCase
console.log('hello'.toUpperCase()); // 'HELLO'
console.log('HELLO'.toLowerCase()); // 'hello'
// trim: remove whitespace
console.log(' spaced '.trim()); // 'spaced'
console.log(' spaced '.trimStart()); // 'spaced '
console.log(' spaced '.trimEnd()); // ' spaced'
// replace / replaceAll: substitute strings
console.log('hello world'.replace('world', 'JS')); // 'hello JS'
console.log('hello world world'.replaceAll('world', 'JS')); // 'hello JS JS'
// split: divide string into array
console.log('a,b,c'.split(',')); // ['a', 'b', 'c']
console.log('hello'.split('')); // ['h', 'e', 'l', 'l', 'o']
// slice / substring: extract portions
const str = 'JavaScript';
console.log(str.slice(0, 4)); // 'Java'
console.log(str.substring(0, 4)); // 'Java'
Templating and Padding
// Template literals (backticks) — not a method, but essential
const name = 'Alice';
const age = 30;
console.log(`${name} is ${age} years old`); // 'Alice is 30 years old'
// padStart / padEnd: pad strings to length
console.log('5'.padStart(3, '0')); // '005'
console.log('5'.padEnd(3, '0')); // '500'
// repeat: repeat string
console.log('ab'.repeat(3)); // 'ababab'
Object Methods
Introspection and Iteration
const user = {
id: 1,
name: 'Alice',
email: 'alice@example.com'
};
// Object.keys: array of property names
console.log(Object.keys(user)); // ['id', 'name', 'email']
// Object.values: array of property values
console.log(Object.values(user)); // [1, 'Alice', 'alice@example.com']
// Object.entries: array of [key, value] pairs
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Object.hasOwn: check if property exists (modern version of hasOwnProperty)
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'age')); // false
Merging and Extending
const defaults = { timeout: 5000, retries: 3 };
const config = { timeout: 10000 };
// Object.assign: merge objects (mutates first argument)
const merged = Object.assign({}, defaults, config);
console.log(merged); // { timeout: 10000, retries: 3 }
// Spread operator: cleaner syntax
const merged2 = { ...defaults, ...config };
console.log(merged2); // { timeout: 10000, retries: 3 }
// Deep merge (manual recursion required)
function deepMerge(target, source) {
Object.entries(source).forEach(([key, value]) => {
if (value && typeof value === 'object' && !Array.isArray(value)) {
target[key] = target[key] || {};
deepMerge(target[key], value);
} else {
target[key] = value;
}
});
return target;
}
Transformation
const users = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
{ id: 3, name: 'Charlie', role: 'user' }
];
// Create a lookup map by ID
const byId = Object.fromEntries(
users.map(u => [u.id, u])
);
console.log(byId[1]); // { id: 1, name: 'Alice', ... }
// Transform values
const upperNames = Object.fromEntries(
Object.entries({ a: 'alice', b: 'bob' })
.map(([k, v]) => [k, v.toUpperCase()])
);
console.log(upperNames); // { a: 'ALICE', b: 'BOB' }
// Group by property
const byRole = Object.groupBy(users, u => u.role);
console.log(byRole.admin); // [{ id: 1, ... }]
Map and Set
Map: Key-Value Storage
// Map preserves key type and insertion order
const map = new Map<string, number>();
// set: add or update entry
map.set('alice', 30);
map.set('bob', 25);
// get: retrieve value
console.log(map.get('alice')); // 30
// has: check if key exists
console.log(map.has('charlie')); // false
// delete: remove entry
map.delete('bob');
// clear: remove all entries
// map.clear();
// size: number of entries
console.log(map.size); // 1
// Iteration
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Map with object keys (unique by reference)
const keyObj = { id: 1 };
const mapWithObjects = new Map();
mapWithObjects.set(keyObj, 'value');
console.log(mapWithObjects.get(keyObj)); // 'value'
Set: Unique Values
// Set stores unique values (by strict equality)
const set = new Set<string>();
// add: insert value
set.add('alice');
set.add('bob');
set.add('alice'); // Duplicate ignored
// has: check membership
console.log(set.has('alice')); // true
// delete: remove value
set.delete('bob');
// size: number of values
console.log(set.size); // 1
// Iteration
for (const value of set) {
console.log(value);
}
// Convert array to set (deduplicate)
const arr = [1, 2, 2, 3, 3, 3];
const unique = Array.from(new Set(arr));
console.log(unique); // [1, 2, 3]
Set Methods (ES2024)
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
// union: combine all elements
const all = setA.union(setB);
console.log(all); // Set(4) { 1, 2, 3, 4 }
// intersection: common elements
const common = setA.intersection(setB);
console.log(common); // Set(2) { 2, 3 }
// difference: in A but not B
const onlyInA = setA.difference(setB);
console.log(onlyInA); // Set(1) { 1 }
// isSubsetOf / isSupersetOf / isDisjointFrom
console.log(setA.isSubsetOf(setB)); // false
console.log(setA.isSupersetOf(new Set([1, 2]))); // true
Promise Methods
Creation and Chaining
// new Promise: create a resolvable promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 100);
});
// .then: handle success
promise.then(result => {
console.log(result); // 'done'
});
// .catch: handle error
promise.catch(error => {
console.error(error.message);
});
// .finally: execute code regardless of outcome
promise.finally(() => {
console.log('cleanup');
});
Composition
// Promise.all: wait for all promises
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(([a, b, c]) => {
console.log(a, b, c); // 1 2 3
});
// Promise.race: return first settled promise
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('timeout')), 1000)
);
const request = fetch('/api/data');
Promise.race([request, timeout])
.catch(error => console.error(error));
// Promise.allSettled: wait for all, even if some fail
Promise.allSettled([p1, p2, Promise.reject('error')])
.then(results => {
console.log(results);
// [
// { status: 'fulfilled', value: 1 },
// { status: 'fulfilled', value: 2 },
// { status: 'rejected', reason: 'error' }
// ]
});
// Promise.any: return first fulfilled promise
Promise.any([Promise.reject('a'), Promise.resolve('b')])
.then(result => console.log(result)); // 'b'
Promise.withResolvers() (ES2024)
// Create resolvable promise without constructor
const { promise, resolve, reject } = Promise.withResolvers();
// Resolve externally
setTimeout(() => resolve('done'), 100);
const result = await promise;
console.log(result); // 'done'
Conclusion
These methods form the backbone of JavaScript programming. Master destructuring, Array operations, async patterns, and Map/Set data structures, and you'll handle 90% of common tasks efficiently. Keep this reference nearby—you'll find yourself returning to it frequently. For cutting-edge features like Iterator helpers and Record/Tuple, stay tuned to TC39 proposals as they mature into standards.