JavaScript Cheatsheet

Arrays

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

Creating Arrays

// Array literal — preferred
const a = [1, 2, 3];
const b = [];                    // empty
const c = [1, , 3];             // sparse (hole at index 1), avoid

// Array constructor
new Array(3)            // [ <3 empty>, ] — length 3, no values
new Array(1, 2, 3)      // [1, 2, 3]
Array(3).fill(0)        // [0, 0, 0]

// Array.of — always creates array of its arguments
Array.of(3)             // [3]  (not length-3 array)
Array.of(1, 2, 3)       // [1, 2, 3]

// Array.from — from iterable or array-like + optional map function
Array.from("hello")              // ["h","e","l","l","o"]
Array.from({length: 3}, (_, i) => i)  // [0, 1, 2]
Array.from(new Set([1, 2, 3]))   // [1, 2, 3]
Array.from(new Map([["a",1]]))   // [["a",1]]
Array.from(document.querySelectorAll("div"))

// Spread
const d = [...a, 4, 5];  // [1, 2, 3, 4, 5]
const e = [...a];         // shallow copy

Accessing and Modifying

const arr = [10, 20, 30, 40, 50];

arr[0]          // 10  (first)
arr[4]          // 50  (last)
arr[arr.length - 1] // 50  (last, dynamic)
arr.at(-1)      // 50  (ES2022 — negative index)
arr.at(-2)      // 40

arr.length      // 5
arr[10] = 99    // sparse array — length becomes 11

// Modifying
arr[1] = 25;    // [10, 25, 30, 40, 50]

// Destructuring
const [first, second, ...rest] = arr;
// first = 10, second = 25, rest = [30, 40, 50]

Stack and Queue Methods (mutating)

const arr = [1, 2, 3];

// Stack (LIFO)
arr.push(4)     // adds to end → returns new length: 4. arr = [1,2,3,4]
arr.pop()       // removes from end → returns 4. arr = [1,2,3]

// Queue (FIFO)
arr.unshift(0)  // adds to start → returns new length: 4. arr = [0,1,2,3]
arr.shift()     // removes from start → returns 0. arr = [1,2,3]

// push/unshift accept multiple args
arr.push(4, 5, 6);
arr.unshift(-2, -1, 0);

splice — The Swiss Army Knife (mutating)

const arr = ["a", "b", "c", "d", "e"];

// splice(start, deleteCount, ...items)
arr.splice(1, 0, "x")     // insert "x" at 1, delete 0 → arr = ["a","x","b","c","d","e"]
arr.splice(2, 1)           // remove 1 at index 2 → returns ["b"]
arr.splice(1, 2, "y","z") // replace 2 at index 1 → returns removed
arr.splice(-2, 1)          // negative index: from end
arr.splice(0)              // clear array, return all elements

slice — Non-Mutating Extraction

const arr = [1, 2, 3, 4, 5];

arr.slice()        // [1,2,3,4,5]  shallow copy
arr.slice(1)       // [2,3,4,5]
arr.slice(1, 3)    // [2,3]  (end is exclusive)
arr.slice(-2)      // [4,5]  (from end)
arr.slice(1, -1)   // [2,3,4]

Searching

const arr = [10, 20, 30, 20, 10];

// By value
arr.indexOf(20)         // 1  (first occurrence, or -1)
arr.lastIndexOf(20)     // 3
arr.includes(30)        // true

// By predicate
arr.find(x => x > 15)       // 20  (first match or undefined)
arr.findIndex(x => x > 15)  // 1   (first match index or -1)
arr.findLast(x => x < 25)   // 20  (ES2023)
arr.findLastIndex(x => x < 25) // 3 (ES2023)

// Check all / some
arr.some(x => x > 25)   // true  (at least one)
arr.every(x => x > 5)   // true  (all)

Sorting

// Default sort: converts to strings and sorts lexicographically
[10, 2, 1, 20].sort()     // [1, 10, 2, 20]  ← wrong for numbers

// Numeric sort with comparator — comparator returns negative/0/positive
[10, 2, 1, 20].sort((a, b) => a - b)  // [1, 2, 10, 20]  ascending
[10, 2, 1, 20].sort((a, b) => b - a)  // [20, 10, 2, 1]  descending

// String sort
["banana","apple","cherry"].sort()  // alphabetical ascending
["banana","apple","cherry"].sort((a, b) => b.localeCompare(a)); // descending

// Sort by object property
const people = [{ name:"Bob",age:30 }, { name:"Alice",age:25 }];
people.sort((a, b) => a.age - b.age);

// toSorted() — non-mutating (ES2023)
const sorted = arr.toSorted((a, b) => a - b);
// arr unchanged, sorted is new array

Iteration Methods

const arr = [1, 2, 3];

// forEach — execute side effects, returns undefined
arr.forEach((val, i, array) => console.log(i, val));

// map — transform, returns new array of same length
arr.map(x => x * 2)        // [2, 4, 6]
arr.map((x, i) => `${i}:${x}`) // ["0:1","1:2","2:3"]

// filter — keep matching elements
arr.filter(x => x > 1)     // [2, 3]

// reduce — accumulate to single value
arr.reduce((acc, val) => acc + val, 0)         // 6
arr.reduce((acc, val) => acc + val)            // 6  (no initial — uses first)
arr.reduceRight((acc, val) => acc + val, 0)   // 6  (right to left)

// flat and flatMap (ES2019)
[[1,2],[3,4]].flat()          // [1,2,3,4]
[1,[2,[3,[4]]]].flat(Infinity) // [1,2,3,4]
arr.flatMap(x => [x, x * 2]) // [1,2,2,4,3,6]  (map then flat 1 level)

Transformation

const arr = [1, 2, 3, 4, 5];

// concat — combine arrays (non-mutating)
arr.concat([6, 7])         // [1,2,3,4,5,6,7]
arr.concat([6], [7, 8])    // [1,2,3,4,5,6,7,8]
[...arr, 6, 7]             // same with spread

// reverse — mutates in place
arr.reverse()              // [5,4,3,2,1]  arr is now reversed
// toReversed() — non-mutating (ES2023)
const rev = arr.toReversed();

// fill — fill range with value (mutates)
new Array(5).fill(0)       // [0,0,0,0,0]
arr.fill(0, 2, 4)          // fill 0 from index 2 to 3
// toFilled() doesn't exist — fill always mutates

// copyWithin — copy part of array to another position (mutates)
[1,2,3,4,5].copyWithin(1, 3) // [1,4,5,4,5]  (copy from 3 to pos 1)

// toSpliced() — non-mutating splice (ES2023)
arr.toSpliced(1, 2, "a")  // new array with splice applied

Joining and Splitting

const arr = ["a", "b", "c"];
arr.join()          // "a,b,c"  (default separator is comma)
arr.join(" - ")     // "a - b - c"
arr.join("")        // "abc"

"a,b,c".split(",")  // ["a","b","c"]
"hello".split("")   // ["h","e","l","l","o"]

Spread and Rest

// Spread — expand array
Math.max(...[1, 2, 3])     // 3
const copy = [...arr]      // shallow copy
const merged = [...a, ...b]

// Rest — collect remaining
const [first, ...rest] = [1, 2, 3]; // rest = [2, 3]
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }

Checking

Array.isArray([])     // true
Array.isArray({})     // false
Array.isArray("str")  // false

[].length === 0       // empty check
arr.length            // element count (not always — sparse arrays)

Common Patterns

// Unique values
const unique = [...new Set(arr)];
const unique2 = arr.filter((v, i, a) => a.indexOf(v) === i);

// Flatten object array to values
const names = users.map(u => u.name);

// Group by (ES2024)
const grouped = items.groupBy(item => item.category);
// or manual:
const grouped2 = items.reduce((acc, item) => {
  (acc[item.category] ??= []).push(item);
  return acc;
}, {});

// Chunk array into subarrays
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size)
  );

// Zip two arrays
const zip = (a, b) => a.map((val, i) => [val, b[i]]);
zip([1,2,3], ["a","b","c"]); // [[1,"a"],[2,"b"],[3,"c"]]

// Shuffle (Fisher-Yates)
function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

// Sum / average
const sum = arr.reduce((a, b) => a + b, 0);
const avg = sum / arr.length;

Typed Arrays

// For binary data / performance-critical code
new Int8Array(4)
new Uint8Array(4)
new Uint8ClampedArray(4)  // values clamped to 0-255
new Int16Array(4)
new Uint16Array(4)
new Int32Array(4)
new Uint32Array(4)
new Float32Array(4)
new Float64Array(4)
new BigInt64Array(4)
new BigUint64Array(4)

const buf = new ArrayBuffer(16);
const view = new DataView(buf);
view.setInt32(0, 42);
view.getInt32(0); // 42