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

MutatesReturns newReturns value
arr.push(4, 5)Mutates

Add 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()Mutates

Remove and return the last element

const a = [1,2,3]; a.pop(); // returns 3, a = [1,2]

Returns: Removed element (or undefined)

arr.shift()Mutates

Remove 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)Mutates

Add 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)Mutates

Add/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)Mutates

Sort 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()Mutates

Reverse the array in place

[1,2,3].reverse(); // [3,2,1]

Returns: The reversed array (same reference)

arr.fill(0, 1, 3)Mutates

Fill 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)Mutates

Copy 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 new

Extract 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 new

Merge 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 new

Flatten 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 new

Map 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 new

Create 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 new

Create 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 value

Reduce 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 map

Returns: Accumulated value (any type)

arr.reduceRight(fn, initial)Returns value

Like 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 new

Create 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 new

Create 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 new

Spread 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 value

Return 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 value

Return 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 value

Return 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 value

Return 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 value

Return 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 value

Return 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 value

Check 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 value

Return 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 value

Return the last index of a value, or -1

[1,2,3,2].lastIndexOf(2); // 3

Returns: Index number or -1

arr.forEach(fn)Returns value

Iterate 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 value

Access 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 value

Join 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 new

Non-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 value

Return the first index of a substring, or -1

"hello world".indexOf("world"); // 6

Returns: Index number or -1

str.includes(substr)Returns value

Check if the string contains a substring

"hello".includes("ell"); // true

Returns: Boolean

str.startsWith(prefix)Returns value

Check if the string starts with the given prefix

"hello".startsWith("he"); // true

Returns: Boolean

str.endsWith(suffix)Returns value

Check if the string ends with the given suffix

"hello".endsWith("lo"); // true

Returns: Boolean

str.slice(start, end)Returns new

Extract 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 new

Like slice but does not support negative indices

"hello".substring(1, 3); // "el"

Returns: New string

str.toUpperCase() / toLowerCase()Returns new

Convert the string to upper or lower case

"Hello".toUpperCase(); // "HELLO"
"Hello".toLowerCase(); // "hello"

Returns: New string

str.trim() / trimStart() / trimEnd()Returns new

Remove whitespace from both ends, start only, or end only

"  hi  ".trim(); // "hi"
"  hi  ".trimStart(); // "hi  "

Returns: New string

str.replace(pattern, replacement)Returns new

Replace 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 new

Replace all occurrences of a string (ES2021). For regex, /g flag required

"aabaa".replaceAll("a", "x"); // "xxbxx"

Returns: New string

str.split(separator, limit)Returns new

Split 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 new

Pad the start of a string to a target length

"42".padStart(5, "0"); // "00042"

Returns: New string

str.padEnd(length, fill)Returns new

Pad the end of a string to a target length

"hi".padEnd(6, "."); // "hi...."

Returns: New string

str.repeat(count)Returns new

Return a string repeated the given number of times

"ab".repeat(3); // "ababab"

Returns: New string

str.match(regex)Returns value

Match 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 value

Returns 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 value

Access character by index — supports negative indices (ES2022)

"hello".at(-1); // "o"

Returns: Character or undefined

str.localeCompare(other)Returns value

Compare 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 new

Return 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 new

Return an array of the object's own enumerable property values

Object.values({a:1,b:2}); // [1,2]

Returns: Array

Object.entries(obj)Returns new

Return 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 new

Convert 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)Mutates

Shallow-merge one or more source objects into the target. Mutates target

Object.assign({}, obj1, obj2); // safe merge into new obj

Returns: The target object

Object.freeze(obj)Mutates

Make 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 value

Check if an object has a given own property. Safer than hasOwnProperty (ES2022)

Object.hasOwn({a:1}, "a"); // true
Object.hasOwn({a:1}, "toString"); // false

Returns: Boolean

{...obj1, ...obj2}Returns new

Spread operator to shallow-merge objects into a new object

const merged = {...defaults, ...overrides};

Returns: New object

const { a, b = 0, ...rest } = objReturns value

Object destructuring with defaults and rest properties

const {name, age=18} = user;
const {x: aliasX} = obj; // rename on destructure

Returns: Bound variables

obj?.prop — optional chainingReturns value

Access 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 value

Return 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 value

Logical 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 value

Wait 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 value

Resolve 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 new

Deep 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.