JavaScript Cheatsheet

Array Methods

Use this JavaScript reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Quick Reference Table

MethodMutatesReturnsDescription
push(...items)yesnew lengthAdd to end
pop()yesremoved itemRemove from end
unshift(...items)yesnew lengthAdd to start
shift()yesremoved itemRemove from start
splice(i, n, ...items)yesremoved itemsInsert/remove at position
sort(fn?)yesarraySort in place
reverse()yesarrayReverse in place
fill(val, s?, e?)yesarrayFill range with value
copyWithin(t, s?, e?)yesarrayCopy within array
slice(s?, e?)nonew arrayExtract subarray
concat(...args)nonew arrayCombine arrays
flat(depth?)nonew arrayFlatten nested arrays
flatMap(fn)nonew arraymap + flat(1)
map(fn)nonew arrayTransform each element
filter(fn)nonew arrayKeep matching elements
reduce(fn, init?)noanyAccumulate to single value
reduceRight(fn, init?)noanyAccumulate right to left
forEach(fn)noundefinedIterate for side effects
find(fn)noelement/undefinedFirst match
findIndex(fn)noindex/-1Index of first match
findLast(fn)noelement/undefinedLast match (ES2023)
findLastIndex(fn)noindex/-1Index of last match (ES2023)
indexOf(val, from?)noindex/-1First index by value
lastIndexOf(val, from?)noindex/-1Last index by value
includes(val, from?)nobooleanContains check
some(fn)nobooleanAt least one match
every(fn)nobooleanAll match
join(sep?)nostringJoin to string
keys()noiteratorIndex iterator
values()noiteratorValue iterator
entries()noiterator[index, value] iterator
at(i)noelement/undefinedIndex (supports negative)
toSorted(fn?)nonew arrayNon-mutating sort (ES2023)
toReversed()nonew arrayNon-mutating reverse (ES2023)
toSpliced(i,n,...items)nonew arrayNon-mutating splice (ES2023)
with(i, val)nonew arrayNon-mutating index replace (ES2023)

Mutating Methods

push / pop / unshift / shift

const arr = [2, 3];
arr.push(4, 5)       // 4 — returns new length; arr = [2,3,4,5]
arr.pop()            // 5 — returns popped; arr = [2,3,4]
arr.unshift(0, 1)    // 5 — returns new length; arr = [0,1,2,3,4]
arr.shift()          // 0 — returns shifted; arr = [1,2,3,4]

splice

// splice(startIndex, deleteCount, ...itemsToInsert)
const a = ["a","b","c","d"];
a.splice(1, 2)          // returns ["b","c"]; a = ["a","d"]
a.splice(1, 0, "x","y") // returns []; a = ["a","x","y","d"]
a.splice(2, 1, "z")     // returns ["y"]; a = ["a","x","z","d"]
a.splice(-1, 1)         // remove last; same as pop
a.splice(0)             // remove all, return all

sort

// Comparator: negative = a before b, 0 = equal, positive = b before a
[3,1,4,1,5].sort((a,b) => a - b)     // [1,1,3,4,5]  ascending
[3,1,4,1,5].sort((a,b) => b - a)     // [5,4,3,1,1]  descending
["c","a","b"].sort()                   // ["a","b","c"]  default (lexicographic)
["c","a","b"].sort((a,b) => b.localeCompare(a))  // descending

// Sort by property
users.sort((a, b) => a.age - b.age);
users.sort((a, b) => a.name.localeCompare(b.name));

// Stable sort is guaranteed (ES2019+)

fill / reverse / copyWithin

new Array(5).fill(0)       // [0,0,0,0,0]
[1,2,3,4,5].fill(0, 2, 4)  // [1,2,0,0,5]  (fill index 2..3)
[1,2,3].reverse()           // [3,2,1]  (in place)
[1,2,3,4,5].copyWithin(1,3) // [1,4,5,4,5]  copy from 3 to pos 1

Non-Mutating Methods

slice

const a = [1,2,3,4,5];
a.slice()        // [1,2,3,4,5]  (copy)
a.slice(1)       // [2,3,4,5]
a.slice(1,3)     // [2,3]  end is exclusive
a.slice(-2)      // [4,5]
a.slice(1,-1)    // [2,3,4]

concat

[1,2].concat([3,4])          // [1,2,3,4]
[1,2].concat([3],[4,5],[6])  // [1,2,3,4,5,6]
[1,2].concat(3, 4)           // [1,2,3,4]
[...[1,2], ...[3,4]]         // same with spread

flat / flatMap

[1,[2,3],[4]].flat()            // [1,2,3,4]  (depth 1 by default)
[1,[2,[3,[4]]]].flat(2)         // [1,2,3,[4]]
[1,[2,[3,[4]]]].flat(Infinity)  // [1,2,3,4]

// flatMap = map then flat(1)
[1,2,3].flatMap(x => [x, x*2])  // [1,2,2,4,3,6]
["hello world"].flatMap(s => s.split(" ")) // ["hello","world"]

Transformation Methods

map

[1,2,3].map(x => x * 2)              // [2,4,6]
[1,2,3].map((val, i) => `${i}:${val}`) // ["0:1","1:2","2:3"]
[1,2,3].map((val, i, arr) => val / arr.length) // [0.33,0.67,1]

// Map to objects
users.map(u => ({ id: u.id, label: u.name }))

filter

[1,2,3,4,5].filter(x => x > 2)       // [3,4,5]
[1,2,3,4,5].filter(x => x % 2 === 0) // [2,4]
users.filter(u => u.active)
arr.filter(Boolean)                    // remove falsy values
arr.filter(v => v !== undefined)       // remove undefined

reduce / reduceRight

// reduce(fn(accumulator, currentValue, index, array), initialValue)
[1,2,3,4].reduce((sum, n) => sum + n, 0)   // 10
[1,2,3,4].reduce((max, n) => n > max ? n : max, -Infinity) // 4

// Build object from array
["a","b","c"].reduce((obj, char, i) => {
  obj[char] = i;
  return obj;
}, {});
// { a: 0, b: 1, c: 2 }

// Flatten (prefer flat())
[[1,2],[3,4]].reduce((acc, arr) => acc.concat(arr), []) // [1,2,3,4]

// Group by
items.reduce((groups, item) => {
  const key = item.type;
  (groups[key] ??= []).push(item);
  return groups;
}, {});

// reduceRight processes right to left
[1,2,3].reduceRight((acc, n) => acc + n, 0) // 6 (same here, different for strings)
["a","b","c"].reduceRight((acc, s) => acc + s, "") // "cba"

Searching Methods

find / findIndex / findLast / findLastIndex

const arr = [5, 12, 8, 130, 44];

arr.find(x => x > 10)          // 12  (first match or undefined)
arr.findIndex(x => x > 10)     // 1   (first match index or -1)
arr.findLast(x => x > 10)      // 44  (last match, ES2023)
arr.findLastIndex(x => x > 10) // 4   (last match index, ES2023)

const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
users.find(u => u.id === 2)    // { id: 2, name: "Bob" }

indexOf / lastIndexOf / includes

const arr = [1,2,3,2,1];
arr.indexOf(2)         // 1
arr.indexOf(2, 2)      // 3  (search from index 2)
arr.lastIndexOf(2)     // 3
arr.includes(3)        // true
arr.includes(5)        // false
arr.includes(NaN)      // false  (NaN-safe: uses SameValueZero)
[NaN].includes(NaN)    // true   (unlike indexOf which returns -1 for NaN)

some / every

[1,2,3].some(x => x > 2)    // true
[1,2,3].every(x => x > 0)   // true
[].every(x => false)          // true  (vacuously true)
[].some(x => true)            // false (vacuously false)

Iteration Methods

forEach

// Returns undefined — cannot break (use for...of instead)
[1,2,3].forEach((val, index, arr) => {
  console.log(index, val);
});

keys / values / entries

const arr = ["a","b","c"];
[...arr.keys()]    // [0, 1, 2]
[...arr.values()]  // ["a","b","c"]
[...arr.entries()] // [[0,"a"],[1,"b"],[2,"c"]]

// Iterate with index using for...of
for (const [i, val] of arr.entries()) {
  console.log(i, val);
}

ES2023+ Non-Mutating Versions

const arr = [3,1,2];

// toSorted — sort without mutating
const sorted = arr.toSorted((a,b) => a - b); // [1,2,3]
// arr unchanged: [3,1,2]

// toReversed — reverse without mutating
const rev = arr.toReversed(); // [2,1,3]
// arr unchanged: [3,1,2]

// toSpliced — splice without mutating
const spliced = arr.toSpliced(1, 1, 9, 8); // [3,9,8,2]
// arr unchanged

// with — change one index without mutating
const updated = arr.with(0, 99); // [99,1,2]
// arr unchanged

String ↔ Array Conversion

// String to array
"hello".split("")           // ["h","e","l","l","o"]
"a,b,c".split(",")          // ["a","b","c"]
[..."hello"]                // ["h","e","l","l","o"]  (spread)
Array.from("hello")         // ["h","e","l","l","o"]

// Array to string
["a","b","c"].join("")      // "abc"
["a","b","c"].join(", ")    // "a, b, c"
[1,2,3].join("-")           // "1-2-3"
[1,2,3].toString()          // "1,2,3"  (same as join(","))

Set Operations (using arrays)

const a = [1,2,3,4];
const b = [3,4,5,6];

// Union
const union = [...new Set([...a, ...b])]; // [1,2,3,4,5,6]

// Intersection
const intersect = a.filter(x => b.includes(x)); // [3,4]

// Difference (a - b)
const diff = a.filter(x => !b.includes(x)); // [1,2]

// Symmetric difference
const symDiff = [
  ...a.filter(x => !b.includes(x)),
  ...b.filter(x => !a.includes(x)),
]; // [1,2,5,6]

// Unique values
const unique = [...new Set(a)];