Developer Cheatsheet
Copy-ready snippets for JavaScript, regex, Git, APIs, and CSS. Search or filter by category.
Array.map()
Transform every element in an array
const doubled = [1, 2, 3].map(n => n * 2);
// [2, 4, 6]Array.filter()
Keep only elements that pass a test
const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
// [2, 4]Array.reduce()
Reduce an array to a single value
const sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
// 10Array.find()
Get the first element matching a condition
const user = users.find(u => u.id === 42);
// Returns first match or undefinedArray.flat()
Flatten nested arrays
const flat = [1, [2, [3, [4]]]].flat(Infinity);
// [1, 2, 3, 4]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]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]Remove duplicates
Deduplicate an array with Set
const unique = [...new Set([1, 2, 2, 3, 3, 4])];
// [1, 2, 3, 4]Email address
Validate a basic email format
/^[^s@]+@[^s@]+.[^s@]+$/URL
Match http or https URLs
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_+.~#?&//=]*)/US phone number
Match common US phone formats
/^(+1)?[-.s]?(?[0-9]{3})?[-.s]?[0-9]{3}[-.s]?[0-9]{4}$/Date (YYYY-MM-DD)
Match ISO 8601 date format
/^d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01])$/URL slug
Match lowercase slugs with hyphens
/^[a-z0-9]+(?:-[a-z0-9]+)*$/Hex color
Match 3 or 6 digit hex colors
/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/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?)$/Init & first commit
Initialize a repo and make the first commit
git init
git add .
git commit -m "Initial commit"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-featureStash changes
Temporarily save uncommitted changes
git stash # save changes
git stash pop # restore latest stash
git stash list # view all stashesInteractive rebase
Squash or edit the last N commits
git rebase -i HEAD~3
# In editor: pick, squash, reword, dropCherry-pick a commit
Apply a specific commit to the current branch
git cherry-pick <commit-hash>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 changesPretty log
View commit history in a compact graph
git log --oneline --graph --decorate --allFetch 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();
}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();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 };
}
}Common request headers
Auth + content type headers for API calls
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
};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;
}Center with Flexbox
Perfectly center an element horizontally and vertically
.container {
display: flex;
align-items: center;
justify-content: center;
}Responsive grid
Auto-fill grid that adapts to container width
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}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;
}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 custom properties
Define and use CSS variables
:root {
--color-primary: #0ea5e9;
--spacing-md: 1rem;
}
.btn {
background: var(--color-primary);
padding: var(--spacing-md);
}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);
}Sticky header
Keep an element fixed at the top while scrolling
.header {
position: sticky;
top: 0;
z-index: 100;
background: var(--bg);
}