JavaScript Array & String Methods
Complete reference for JS array methods, string methods, object methods, and ES2020+ additions. With examples and return type for every method.
Showing 66 of 66 methods — hover card for copy button
arr.push(4, 5)MutatesAdd one or more elements to the end of an array
const a = [1,2,3]; a.push(4, 5); // a = [1,2,3,4,5]
Returns: New length of the array
arr.pop()MutatesRemove and return the last element
const a = [1,2,3]; a.pop(); // returns 3, a = [1,2]
Returns: Removed element (or undefined)
arr.shift()MutatesRemove and return the first element
const a = [1,2,3]; a.shift(); // returns 1, a = [2,3]
Returns: Removed element (or undefined)
arr.unshift(0)MutatesAdd one or more elements to the start of an array
const a = [1,2,3]; a.unshift(0); // a = [0,1,2,3]
Returns: New length of the array
arr.splice(1, 2)MutatesAdd/remove elements at a given index. splice(start, deleteCount, ...items)
a.splice(1, 2); // remove 2 at index 1 a.splice(1, 0, 'x'); // insert 'x' a.splice(1, 1, 'y'); // replace at index 1
Returns: Array of removed elements
arr.sort((a, b) => a - b)MutatesSort array in place. Without comparator uses lexicographic order
arr.sort(); // lexicographic arr.sort((a,b) => a - b); // numeric asc arr.sort((a,b) => b - a); // numeric desc arr.sort((a,b) => a.name.localeCompare(b.name));
Returns: The sorted array (same reference)
arr.reverse()MutatesReverse the array in place
[1,2,3].reverse(); // [3,2,1]
Returns: The reversed array (same reference)
arr.fill(0, 1, 3)MutatesFill all or a range of elements with a static value
[1,2,3,4].fill(0); // [0,0,0,0] [1,2,3,4].fill(0, 1, 3); // [1,0,0,4]
Returns: The modified array (same reference)
arr.copyWithin(0, 3)MutatesCopy part of the array to another location within the same array
[1,2,3,4,5].copyWithin(0, 3); // [4,5,3,4,5]
Returns: The modified array (same reference)
arr.slice(1, 3)Returns newExtract a portion of the array without modifying the original
[1,2,3,4].slice(1, 3); // [2,3] [1,2,3].slice(-2); // [2,3] [1,2,3].slice(); // shallow copy
Returns: New array with extracted elements
arr.concat([4, 5], [6])Returns newMerge two or more arrays into a new array
[1,2].concat([3,4], [5]); // [1,2,3,4,5]
Returns: New merged array
arr.flat(depth)Returns newFlatten nested arrays up to the given depth (default 1). Use Infinity to flatten fully
[[1,2],[3,[4]]].flat(); // [1,2,3,[4]] [[[1]]].flat(Infinity); // [1]
Returns: New flattened array
arr.flatMap(fn)Returns newMap each element then flatten one level — equivalent to .map().flat(1)
[1,2,3].flatMap(x => [x, x*2]); // [1,2,2,4,3,6] [[1],[2]].flatMap(x => x); // [1,2]
Returns: New array (mapped and flattened one level)
arr.map(fn)Returns newCreate a new array by transforming each element with a callback
[1,2,3].map(x => x * 2); // [2,4,6] [1,2,3].map((x,i) => i); // [0,1,2]
Returns: New array with same length
arr.filter(fn)Returns newCreate a new array with only elements that pass the predicate
[1,2,3,4].filter(x => x > 2); // [3,4] arr.filter(Boolean); // remove falsy values
Returns: New (possibly shorter) array
arr.reduce(fn, initial)Returns valueReduce array to a single value by accumulating a result
[1,2,3].reduce((acc,x) => acc + x, 0); // 6
arr.reduce((acc,x) => ({...acc,[x.id]:x}), {}); // to mapReturns: Accumulated value (any type)
arr.reduceRight(fn, initial)Returns valueLike reduce but iterates from right to left
[[1],[2],[3]].reduceRight((acc,x) => acc.concat(x), []); // [3,2,1]
Returns: Accumulated value (any type)
Array.from(iterable, mapFn)Returns newCreate an array from any iterable or array-like object
Array.from('hello'); // ['h','e','l','l','o']
Array.from({length:5},(_,i)=>i); // [0,1,2,3,4]
Array.from(new Set([1,1,2])); // [1,2]Returns: New array
Array.of(1, 2, 3)Returns newCreate a new array from the given arguments
Array.of(7); // [7] (vs Array(7) which creates 7 empty slots)
Returns: New array
[...arr1, ...arr2]Returns newSpread syntax to merge or shallow-copy arrays
[...a, ...b]; // merge [...arr]; // shallow copy [0, ...arr, 99]; // prepend/append
Returns: New array
arr.find(fn)Returns valueReturn the first element that satisfies the predicate
[1,2,3,4].find(x => x > 2); // 3 arr.find(x => x.id === 5); // first match
Returns: First matching element or undefined
arr.findIndex(fn)Returns valueReturn the index of the first element that satisfies the predicate
[1,2,3,4].findIndex(x => x > 2); // 2 arr.findIndex(x => x.id === 5); // -1 if not found
Returns: Index number or -1
arr.findLast(fn)Returns valueReturn the last element that satisfies the predicate (ES2023)
[1,2,3,4].findLast(x => x < 3); // 2
Returns: Last matching element or undefined
arr.findLastIndex(fn)Returns valueReturn the index of the last matching element (ES2023)
[1,2,3,4].findLastIndex(x => x < 3); // 1
Returns: Index number or -1
arr.some(fn)Returns valueReturn true if at least one element passes the predicate
[1,2,3].some(x => x > 2); // true arr.some(x => x.active); // any active?
Returns: Boolean
arr.every(fn)Returns valueReturn true if all elements pass the predicate
[2,4,6].every(x => x % 2 === 0); // true arr.every(x => x.valid);
Returns: Boolean
arr.includes(value)Returns valueCheck if the array contains a value (uses SameValueZero — works for NaN)
[1,2,3].includes(2); // true [1,NaN].includes(NaN); // true
Returns: Boolean
arr.indexOf(value)Returns valueReturn the first index of a value, or -1. Uses strict equality
[1,2,3,2].indexOf(2); // 1 [1,2,3].indexOf(9); // -1
Returns: Index number or -1
arr.lastIndexOf(value)Returns valueReturn the last index of a value, or -1
[1,2,3,2].lastIndexOf(2); // 3
Returns: Index number or -1
arr.forEach(fn)Returns valueIterate over elements and call a function. Does not return a value
arr.forEach((item, index) => console.log(index, item));
Returns: undefined
arr.at(index)Returns valueAccess element by index — supports negative indices (ES2022)
[1,2,3].at(-1); // 3 (last) [1,2,3].at(0); // 1
Returns: Element or undefined
arr.join(separator)Returns valueJoin all elements into a string with a separator
[1,2,3].join(", "); // "1, 2, 3"
[1,2,3].join(""); // "123"Returns: String
arr.toSorted() / toReversed() / with()Returns newNon-mutating versions of sort, reverse, and splice-replace (ES2023)
arr.toSorted((a,b) => a - b); // sorted, original unchanged arr.toReversed(); // reversed copy arr.with(1, 99); // copy with index 1 replaced by 99
Returns: New array
str.indexOf(substr)Returns valueReturn the first index of a substring, or -1
"hello world".indexOf("world"); // 6Returns: Index number or -1
str.includes(substr)Returns valueCheck if the string contains a substring
"hello".includes("ell"); // trueReturns: Boolean
str.startsWith(prefix)Returns valueCheck if the string starts with the given prefix
"hello".startsWith("he"); // trueReturns: Boolean
str.endsWith(suffix)Returns valueCheck if the string ends with the given suffix
"hello".endsWith("lo"); // trueReturns: Boolean
str.slice(start, end)Returns newExtract a portion of the string. Supports negative indices
"hello".slice(1, 3); // "el" "hello".slice(-3); // "llo"
Returns: New string
str.substring(start, end)Returns newLike slice but does not support negative indices
"hello".substring(1, 3); // "el"
Returns: New string
str.toUpperCase() / toLowerCase()Returns newConvert the string to upper or lower case
"Hello".toUpperCase(); // "HELLO" "Hello".toLowerCase(); // "hello"
Returns: New string
str.trim() / trimStart() / trimEnd()Returns newRemove whitespace from both ends, start only, or end only
" hi ".trim(); // "hi" " hi ".trimStart(); // "hi "
Returns: New string
str.replace(pattern, replacement)Returns newReplace first match (string) or all matches (regex with /g flag)
"aabaa".replace("a", "x"); // "xabaa"
"aabaa".replace(/a/g, "x"); // "xxbxx"Returns: New string
str.replaceAll(pattern, replacement)Returns newReplace all occurrences of a string (ES2021). For regex, /g flag required
"aabaa".replaceAll("a", "x"); // "xxbxx"Returns: New string
str.split(separator, limit)Returns newSplit a string into an array by a separator
"a,b,c".split(","); // ["a","b","c"]
"hi".split(""); // ["h","i"]
"a b c".split(" ", 2); // ["a","b"]Returns: Array of strings
str.padStart(length, fill)Returns newPad the start of a string to a target length
"42".padStart(5, "0"); // "00042"
Returns: New string
str.padEnd(length, fill)Returns newPad the end of a string to a target length
"hi".padEnd(6, "."); // "hi...."
Returns: New string
str.repeat(count)Returns newReturn a string repeated the given number of times
"ab".repeat(3); // "ababab"
Returns: New string
str.match(regex)Returns valueMatch against a regular expression. With /g returns all matches
"test 123 foo 456".match(/\d+/g); // ["123","456"]
Returns: Array or null
str.matchAll(regex)Returns valueReturns iterator of all match objects (requires /g flag). ES2020
for (const m of "a1b2".matchAll(/(\w)(\d)/g)) console.log(m[1], m[2]);
Returns: Iterator of match objects
str.at(index)Returns valueAccess character by index — supports negative indices (ES2022)
"hello".at(-1); // "o"
Returns: Character or undefined
str.localeCompare(other)Returns valueCompare two strings in locale-aware order for sorting
["banana","apple","cherry"].sort((a,b) => a.localeCompare(b));
Returns: -1, 0, or 1
Object.keys(obj)Returns newReturn an array of the object's own enumerable property keys
Object.keys({a:1,b:2}); // ["a","b"]Returns: Array of strings
Object.values(obj)Returns newReturn an array of the object's own enumerable property values
Object.values({a:1,b:2}); // [1,2]Returns: Array
Object.entries(obj)Returns newReturn an array of [key, value] pairs
Object.entries({a:1,b:2}); // [["a",1],["b",2]]Returns: Array of [key, value] pairs
Object.fromEntries(entries)Returns newConvert an array of [key, value] pairs (or a Map) back to an object
Object.fromEntries([["a",1],["b",2]]); // {a:1,b:2}
Object.fromEntries(map);Returns: New object
Object.assign(target, ...sources)MutatesShallow-merge one or more source objects into the target. Mutates target
Object.assign({}, obj1, obj2); // safe merge into new objReturns: The target object
Object.freeze(obj)MutatesMake an object immutable — no add/delete/modify. Shallow only
const o = Object.freeze({x:1});
o.x = 99; // silently ignored (strict: throws)Returns: The frozen object
Object.hasOwn(obj, key)Returns valueCheck if an object has a given own property. Safer than hasOwnProperty (ES2022)
Object.hasOwn({a:1}, "a"); // true
Object.hasOwn({a:1}, "toString"); // falseReturns: Boolean
{...obj1, ...obj2}Returns newSpread operator to shallow-merge objects into a new object
const merged = {...defaults, ...overrides};Returns: New object
const { a, b = 0, ...rest } = objReturns valueObject destructuring with defaults and rest properties
const {name, age=18} = user;
const {x: aliasX} = obj; // rename on destructureReturns: Bound variables
obj?.prop — optional chainingReturns valueAccess nested properties safely — returns undefined instead of throwing if any step is null/undefined (ES2020)
user?.address?.city arr?.[0] fn?.() // call only if fn is a function
Returns: Value or undefined
x ?? 'default' — nullish coalescingReturns valueReturn right-hand side only when left is null or undefined (not falsy). ES2020
const port = config.port ?? 3000; // 0 is kept! x ??= "default"; // assign if null/undefined (ES2021)
Returns: Left or right value
x ||= / x &&= / x ??=Returns valueLogical assignment operators (ES2021)
x ||= 'default'; // assign if falsy x &&= newVal; // assign if truthy x ??= 0; // assign if null/undefined
Returns: Assigned value
Promise.allSettled([p1, p2])Returns valueWait for all promises to settle (resolve or reject). Never rejects (ES2020)
const results = await Promise.allSettled([p1, p2]); results[0].status; // 'fulfilled' | 'rejected'
Returns: Array of {status, value/reason}
Promise.any([p1, p2])Returns valueResolve with the first fulfilled promise. Rejects only if all reject (ES2021)
const first = await Promise.any([fast(), slow()]);
Returns: First resolved value
structuredClone(obj)Returns newDeep clone an object natively — handles nested objects, Arrays, Map, Set, Date, etc. (ES2022)
const copy = structuredClone(obj); // Functions are NOT cloned
Returns: Deep clone
Frequently Asked Questions
What is the difference between map and forEach?
map returns a new array containing the return value of the callback for each element — it is the correct choice when you want to transform an array. forEach does not return anything (returns undefined) and is intended purely for side effects such as logging or updating external state. Because map produces a new array, it is preferred in functional patterns and can be chained with filter, reduce, etc. forEach cannot be chained.
What is the difference between slice and splice?
slice is non-mutating — it extracts a portion of an array and returns a new array, leaving the original unchanged. splice mutates the original array by removing, replacing, or inserting elements at a given index and returns the removed elements. A common mnemonic: slice is like slicing bread (you get a piece but the loaf remains), splice is like splicing film (you cut and modify the original).
How do I remove duplicates from an array?
The cleanest modern approach is Array.from(new Set(arr)) or [...new Set(arr)]. A Set only stores unique values, so converting the array to a Set and back removes all duplicates. For arrays of objects where you want to deduplicate by a specific property, use reduce: arr.reduce((acc, item) => acc.some(x => x.id === item.id) ? acc : [...acc, item], []). For large arrays, using a Map keyed by the unique property is more efficient.
What is the best way to deep clone an object in JavaScript?
In modern JavaScript (ES2022+), use structuredClone(obj). It handles nested objects, arrays, Map, Set, Date, RegExp, and circular references correctly. The older JSON.parse(JSON.stringify(obj)) trick works for plain data but loses undefined values, functions, Dates become strings, and Map/Set are not handled. For environments that do not support structuredClone, consider a utility library like Lodash cloneDeep.
What is the difference between find and filter?
find returns the first element that satisfies the predicate (or undefined if none match) — it stops iterating as soon as a match is found. filter returns a new array containing all elements that satisfy the predicate. Use find when you only need the first match and want to stop early (more efficient for large arrays), and use filter when you need all matching elements.