Cheatsheet - JavaScript

Arrays

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

// Non-mutating transformations
arr.map((x) => x * 2);                 // [2, 4, 6, 8, 10]
arr.filter((x) => x % 2 === 0);        // [2, 4]
arr.reduce((acc, x) => acc + x, 0);    // 15
arr.find((x) => x > 3);                // 4 (first match or undefined)
arr.findIndex((x) => x > 3);           // 3 (index or -1)
arr.some((x) => x < 0);                // false
arr.every((x) => x > 0);               // true
arr.flatMap((x) => [x, x * 10]);       // [1, 10, 2, 20, ...]

// Searching & slicing
arr.includes(3);                       // true
arr.indexOf(3);                        // 2
arr.slice(1, 4);                       // [2, 3, 4] (shallow copy from start to end-1)
arr.at(-1);                            // 5 (negative index support)

// Mutating methods
arr.push(6);                           // Add to end
arr.pop();                             // Remove from end
arr.unshift(0);                        // Add to start
arr.shift();                           // Remove from start
arr.splice(startIndex, deleteCount, ...items); // Insert/remove in-place
arr.sort((a, b) => a - b);             // Numeric sort ascending

// ES2023 non-mutating counterparts
const sorted = arr.toSorted((a, b) => a - b);
const reversed = arr.toReversed();

// Array creation & cloning
const clone = [...arr];
const zeros = new Array(5).fill(0);
const fromRange = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
Array.isArray(arr);                    // true

Objects

const key = 'role';
const user = {
  id: 1,
  name: 'Sam',
  [key]: 'admin',                      // Computed property name
};

// Accessing properties
user.name;                             // 'Sam'
user['id'];                            // 1

// Keys, values, entries
Object.keys(user);                     // ['id', 'name', 'role']
Object.values(user);                   // [1, 'Sam', 'admin']
Object.entries(user);                  // [['id', 1], ['name', 'Sam'], ['role', 'admin']]
Object.fromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }

// Merging & cloning
const updated = { ...user, active: true };
const merged = Object.assign({}, user, { level: 2 });

// Check property existence
'name' in user;                        // true (including prototype chain)
Object.hasOwn(user, 'name');           // true (own property check, replaces hasOwnProperty)

Modern Operators (?., ??, ??=)

// Optional chaining (?.)
const street = user?.address?.street;  // undefined without throwing error
const first = arr?.[0];
const res = obj.fetchData?.();         // Calls function only if it exists

// Nullish coalescing (??)
// Returns right-hand side ONLY if left is null or undefined (preserves 0, false, '')
const port = process.env.PORT ?? 3000;
const count = 0 ?? 10;                 // 0
const fallback = 0 || 10;              // 10 (|| checks falsy, overriding 0 and '')

// Logical assignment operators
let config = {};
config.timeout ??= 5000;               // Assigns only if nullish
config.active &&= false;               // Assigns only if truthy
config.title ||= 'Default';            // Assigns only if falsy

Destructuring & Spread

// Object destructuring with renaming and defaults
const { id, name: userName, status = 'pending', ...extra } = user;

// Array destructuring with rest
const [first, second, ...rest] = [10, 20, 30, 40];

// Swapping variables in-place
let a = 1, b = 2;
[a, b] = [b, a];

// Function argument destructuring
function render({ title, visible = true }) {
  console.log(title, visible);
}

Promises & Async / Await

// Async / Await with try-catch
async function fetchData(url) {
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('Fetch error:', err.message);
    throw err;
  }
}

// Creating a promise
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Concurrent promise combinators
const [users, posts] = await Promise.all([
  fetchUsers(),
  fetchPosts(),
]);                                    // Fails fast if any promise rejects

const results = await Promise.allSettled([
  fetchUsers(),
  fetchPosts(),
]);                                    // Waits for all; returns [{status: 'fulfilled', value}, {status: 'rejected', reason}]

const fastest = await Promise.race([p1, p2]); // Resolves/rejects with the fastest promise

Set & Map

Set (Unique Values)

const set = new Set([1, 2, 2, 3]);    // Set(3) { 1, 2, 3 }
set.add(4);
set.has(2);                           // true
set.delete(3);                        // Removes 3
set.size;                             // 3

// Deduplicate an array
const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]

Map (Key-Value Store with Any Key Type)

const map = new Map();
const objKey = { id: 1 };

map.set(objKey, 'metadata');
map.set('total', 100);

map.get(objKey);                      // 'metadata'
map.has('total');                     // true
map.delete('total');
map.size;                             // 1

// Iteration
for (const [k, v] of map) {
  console.log(k, v);
}

Strings

const str = '  Hello, JavaScript!  ';

// Inspection & matching
str.includes('Java');                  // true
str.startsWith('  Hello');             // true
str.endsWith('!  ');                   // true
str.indexOf('Script');                 // 13

// Transformations
str.trim();                            // 'Hello, JavaScript!'
str.toLowerCase();                     // '  hello, javascript!  '
str.slice(2, 7);                       // 'Hello'
str.split(', ');                       // ['  Hello', 'JavaScript!  ']

// Replacement
'foo bar foo'.replaceAll('foo', 'qux'); // 'qux bar qux'
'item'.padStart(8, '0');               // '0000item'

// Template literals
const name = 'Alice';
const age = 30;
const bio = `Name: ${name}, Next year: ${age + 1}`;

JSON

const data = { id: 1, name: 'Config', active: true };

// Serialize
const jsonString = JSON.stringify(data);
const formatted = JSON.stringify(data, null, 2); // Pretty-printed with 2 spaces

// Parse
const obj = JSON.parse(jsonString);