Developer Cheatsheet

Copy-ready snippets for JavaScript, regex, Git, APIs, and CSS. Search or filter by category.

JavaScript Arrays

Array.map()

Transform every element in an array

const doubled = [1, 2, 3].map(n => n * 2);
// [2, 4, 6]
JavaScript Arrays

Array.filter()

Keep only elements that pass a test

const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
// [2, 4]
JavaScript Arrays

Array.reduce()

Reduce an array to a single value

const sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
// 10
JavaScript Arrays

Array.find()

Get the first element matching a condition

const user = users.find(u => u.id === 42);
// Returns first match or undefined
JavaScript Arrays

Array.flat()

Flatten nested arrays

const flat = [1, [2, [3, [4]]]].flat(Infinity);
// [1, 2, 3, 4]
JavaScript Arrays

Spread & merge arrays

Combine arrays or clone without mutation

const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];  // [1, 2, 3, 4]
const clone  = [...a];        // [1, 2]
JavaScript Arrays

Array destructuring

Unpack values from arrays into variables

const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]
JavaScript Arrays

Remove duplicates

Deduplicate an array with Set

const unique = [...new Set([1, 2, 2, 3, 3, 4])];
// [1, 2, 3, 4]
Regex Patterns

Email address

Validate a basic email format

/^[^s@]+@[^s@]+.[^s@]+$/
Regex Patterns

URL

Match http or https URLs

/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_+.~#?&//=]*)/
Regex Patterns

US phone number

Match common US phone formats

/^(+1)?[-.s]?(?[0-9]{3})?[-.s]?[0-9]{3}[-.s]?[0-9]{4}$/
Regex Patterns

Date (YYYY-MM-DD)

Match ISO 8601 date format

/^d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01])$/
Regex Patterns

URL slug

Match lowercase slugs with hyphens

/^[a-z0-9]+(?:-[a-z0-9]+)*$/
Regex Patterns

Hex color

Match 3 or 6 digit hex colors

/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
Regex Patterns

IPv4 address

Match a valid IPv4 address

/^((25[0-5]|2[0-4]d|[01]?dd?).){3}(25[0-5]|2[0-4]d|[01]?dd?)$/
Git Commands

Init & first commit

Initialize a repo and make the first commit

git init
git add .
git commit -m "Initial commit"
Git Commands

Create & switch branch

Create a new branch and switch to it

git checkout -b feature/my-feature
# or (Git 2.23+)
git switch -c feature/my-feature
Git Commands

Stash changes

Temporarily save uncommitted changes

git stash          # save changes
git stash pop      # restore latest stash
git stash list     # view all stashes
Git Commands

Interactive rebase

Squash or edit the last N commits

git rebase -i HEAD~3
# In editor: pick, squash, reword, drop
Git Commands

Cherry-pick a commit

Apply a specific commit to the current branch

git cherry-pick <commit-hash>
Git Commands

Undo last commit

Reset to previous commit, keeping changes staged

git reset --soft HEAD~1  # keep changes staged
git reset --mixed HEAD~1 # keep changes unstaged
git reset --hard HEAD~1  # discard changes
Git Commands

Pretty log

View commit history in a compact graph

git log --oneline --graph --decorate --all
JSON / API

Fetch GET request

Basic GET with async/await and error handling

async function getData(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
JSON / API

Fetch POST request

POST JSON data with headers

const res = await fetch('/api/endpoint', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ key: 'value' }),
});
const data = await res.json();
JSON / API

Safe JSON.parse

Parse JSON without crashing on bad input

function safeParse(str) {
  try {
    return { data: JSON.parse(str), error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}
JSON / API

Common request headers

Auth + content type headers for API calls

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${token}`,
  'Accept': 'application/json',
};
JSON / API

Fetch with timeout

Cancel a fetch request after N milliseconds

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);

try {
  const res = await fetch(url, { signal: controller.signal });
  clearTimeout(timeout);
  return res.json();
} catch (e) {
  if (e.name === 'AbortError') throw new Error('Request timed out');
  throw e;
}
CSS Tricks

Center with Flexbox

Perfectly center an element horizontally and vertically

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
CSS Tricks

Responsive grid

Auto-fill grid that adapts to container width

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
}
CSS Tricks

Truncate text

Cut off overflow text with an ellipsis

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Multi-line (2 lines) */
.clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
CSS Tricks

Fluid font size

Scale font size smoothly between two breakpoints

.heading {
  /* min 1rem, max 2.5rem, fluid between 320px–1200px */
  font-size: clamp(1rem, 2.5vw, 2.5rem);
}
CSS Tricks

CSS custom properties

Define and use CSS variables

:root {
  --color-primary: #0ea5e9;
  --spacing-md: 1rem;
}

.btn {
  background: var(--color-primary);
  padding: var(--spacing-md);
}
CSS Tricks

Dark mode with prefers-color-scheme

Automatically switch styles based on OS preference

:root {
  --bg: #ffffff;
  --text: #111111;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0f0f0f;
    --text: #f5f5f5;
  }
}

body {
  background: var(--bg);
  color: var(--text);
}
CSS Tricks

Sticky header

Keep an element fixed at the top while scrolling

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: var(--bg);
}